You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Creationmy_list= []
my_list= [1, 2, 3, 4, 5]
my_list=list(range(5)) # [0, 1, 2, 3, 4]# Operationsmy_list.append(6) # Add to end: [1, 2, 3, 4, 5, 6]my_list.insert(0, 0) # Insert at index: [0, 1, 2, 3, 4, 5, 6]my_list.pop() # Remove and return last item: 6my_list.pop(0) # Remove at index: 0my_list.remove(4) # Remove first occurrence: [1, 2, 3, 5]delmy_list[1] # Delete at index: [1, 3, 5]# Slicingmy_list[start:end:step] # start inclusive, end exclusivemy_list[::-1] # Reverse listmy_list[2:] # From index 2 to endmy_list[:3] # From start to index 3 (exclusive)# List comprehensionsquares= [x**2forxinrange(10)]
even_squares= [x**2forxinrange(10) ifx%2==0]
Dictionaries
# Creationmy_dict= {}
my_dict= {'key1': 'value1', 'key2': 'value2'}
my_dict=dict(key1='value1', key2='value2')
# Operationsmy_dict['key3'] ='value3'# Add or updatemy_dict.get('key4', 'default') # Get with defaultmy_dict.pop('key1') # Remove and returnmy_dict.keys() # View of keysmy_dict.values() # View of valuesmy_dict.items() # View of (key, value) pairs# Dictionary comprehensionsquare_dict= {x: x**2forxinrange(5)}
Sets
# Creationmy_set=set()
my_set= {1, 2, 3, 4, 5}
# Operationsmy_set.add(6) # Add elementmy_set.remove(1) # Remove element (raises error if not present)my_set.discard(10) # Remove if present (no error if absent)my_set.pop() # Remove and return arbitrary element# Set operationsset1= {1, 2, 3}
set2= {3, 4, 5}
set1|set2# Union: {1, 2, 3, 4, 5}set1&set2# Intersection: {3}set1-set2# Difference: {1, 2}set1^set2# Symmetric difference: {1, 2, 4, 5}
Tuples
# Creation (immutable)my_tuple= ()
my_tuple= (1, 2, 3)
my_tuple=1, 2, 3# Parentheses optional# Single element tuple needs trailing commasingle_tuple= (1,)
Deque (Double-ended Queue)
fromcollectionsimportdeque# Creationmy_deque=deque([1, 2, 3])
# Operations (O(1) complexity)my_deque.append(4) # Add to rightmy_deque.appendleft(0) # Add to leftmy_deque.pop() # Remove from rightmy_deque.popleft() # Remove from left
Heaps (Priority Queue)
importheapq# Create a min heapheap= []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
heapq.heappush(heap, 2)
# Pop smallest elementsmallest=heapq.heappop(heap) # 1# Convert list to heap in-placenumbers= [3, 1, 5, 2, 4]
heapq.heapify(numbers) # Now a min heap# For max heap, negate valuesmax_heap= []
heapq.heappush(max_heap, -3)
max_val=-heapq.heappop(max_heap) # 3
# Swap valuesa, b=b, a# Flatten list of listsflattened= [itemforsublistinnested_listforiteminsublist]
# Get frequency countfromcollectionsimportCounterfrequencies=Counter([1, 2, 2, 3, 3, 3]) # Counter({3: 3, 2: 2, 1: 1})# Find most common elementmost_common=max(set(my_list), key=my_list.count)
# Check if all/any elements satisfy conditionall_positive=all(x>0forxinnumbers)
any_positive=any(x>0forxinnumbers)
# Useful built-in functionsenumerate(iterable) # Returns (index, value) pairszip(list1, list2) # Combines multiple iterablesmap(function, iterable) # Applies function to each elementfilter(function, iterable) # Filters elements by functionrange(start, stop, step) # Creates a sequence of numbers# String operationsmy_string.strip() # Remove whitespace from endsmy_string.split(',') # Split by delimiter','.join(['a', 'b', 'c']) # Join list into stringmy_string.lower()/upper() # Convert case
Common Regex Patterns
importre# Basic patternsre.search(r'\d+', text) # Find digitsre.findall(r'[a-zA-Z]+', text) # Find wordsre.sub(r'\s+', ' ', text) # Replace multiple spaces with one
Debugging Helpers
# Print with labeled debug infoprint(f"Debug - variable: {variable}, type: {type(variable)}")
# Time executionimporttimestart=time.time()
# ... code to time ...end=time.time()
print(f"Execution time: {end-start} seconds")
About
Materials to help study for Python coding interviews