Skip to content

Instantly share code, notes, and snippets.

@overdrivemachines
Last active August 14, 2023 04:10
Show Gist options
  • Save overdrivemachines/5ef980d6e2c1559be238e9b888343651 to your computer and use it in GitHub Desktop.
Save overdrivemachines/5ef980d6e2c1559be238e9b888343651 to your computer and use it in GitHub Desktop.
Python Guide

Python Guide

Naming Conventions

  • Variables, Functions: snake_case
  • Class Names: CamelCase, MyClass, PersonDetails

Data Structures

Lists

my_list = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed_types = [1, "hello", 3.14, True]
nested_list = [[1, 2, 3], [4, 5, 6]]
print(my_list[-1])  # Output: 5 (last element)
print(my_list[-2])  # Output: 4 (second-to-last element)
sub_list = my_list[1:4]  # Get elements at indices 1, 2, and 3
print(sub_list)  # Output: [2, 3, 4]

Modifying a List:

my_list.append(6)  # Add an element to the end
my_list.insert(1, 7)  # Insert 7 at index 1
my_list.remove(4)  # Remove the element with value 4
my_list.pop(3)  # Remove and return the element at index 3

Stack implemented using a List

stack = []  # Initialize an empty list as a stack

# Push elements onto the stack using the append() method
stack.append(10)
stack.append(20)
stack.append(30)

# Pop elements from the stack using the pop() method
popped_item = stack.pop()  # Removes and returns 30
print(popped_item)

Stack implemented using collections.deque

from collections import deque

stack = deque()  # Initialize an empty deque as a stack

stack.append(10)
stack.append(20)
stack.append(30)

popped_item = stack.pop()
print(popped_item) # 30

popped_item = stack.pop()
print(popped_item) # 20

print(stack)  # Remaining stack: deque([10])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment