Creating Lists
# Create an empty list
empty_list = []
# Create a list with elements
fruits = ['apple', 'orange', 'banana']
# Create a list of numbers
numbers = [1, 2, 3, 4, 5]
# Create a mixed-type list
mixed_list = [1, 'apple', 3.14, True]
Accessing Elements
# Accessing elements by index
first_fruit = fruits[0]
second_number = numbers[1]
# Negative indexing
last_fruit = fruits[-1]
# Slicing a list
sliced_fruits = fruits[1:3] # Returns ['orange', 'banana']
Modifying Lists
# Adding elements to a list
fruits.append('grape') # Adds 'grape' to the end
fruits.insert(1, 'kiwi') # Inserts 'kiwi' at index 1
# Removing elements
fruits.remove('orange') # Removes 'orange'
popped_fruit = fruits.pop() # Removes and returns the last element
# Updating elements
fruits[1] = 'pear' # Updates element at index 1
List Operations
# Adding elements to a list
fruits.append('grape') # Adds 'grape' to the end
fruits.insert(1, 'kiwi') # Inserts 'kiwi' at index 1
# Removing elements
fruits.remove('orange') # Removes 'orange'
popped_fruit = fruits.pop() # Removes and returns the last element
# Updating elements
fruits[1] = 'pear' # Updates element at index 1
List Methods
# Sorting a list
fruits.sort()
# Reversing a list
fruits.reverse()
# Finding index of an element
index_of_banana = fruits.index('banana')
# Count occurrences of an element
num_apples = fruits.count('apple')
List Comprehensions
# Creating a new list using a comprehension
squared_numbers = [x**2 for x in range(1, 6)]
# Filtering elements with a condition
even_numbers = [x for x in range(1, 6) if x % 2 == 0]
Common Pitfalls
# Modifying a list while iterating
for fruit in fruits:
fruits.remove(fruit) # This can lead to unexpected behavior
# Mutating a list in a function
def modify_list(my_list):
my_list.append('new_element')
original_list = [1, 2, 3]
modify_list(original_list)
# original_list is now [1, 2, 3, 'new_element']
Nested Lists
# Creating a nested list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Accessing elements in a nested list
element_5 = matrix[1][1] # Retrieves the value 5
List Concatenation and Repetition
# Combining lists with different data types
combined_data = fruits + numbers + ['kiwi', 6]
# Repetition with nested lists
repeated_matrix = matrix * 2
List Slicing with Stride
# Slicing with a step (stride)
even_indices = combined_data[::2] # Gets elements at even indices
List Methods for Modification
# Extend a list with another list
fruits.extend(['grape', 'watermelon'])
# Clear all elements in a list
fruits.clear()
List Comprehensions with Conditionals
# Using if-else in a list comprehension
even_or_odd = ['even' if num % 2 == 0 else 'odd' for num in numbers]
Zip Function
# Combining two lists into pairs
pairs = list(zip(fruits, numbers))
# Result: [('apple', 1), ('orange', 2), ('banana', 3)]
List Copying
# Copying a list
original_list = [1, 2, 3]
copied_list = original_list.copy()
Removing Duplicates
# Removing duplicates while maintaining order
unique_fruits = list(dict.fromkeys(fruits))
List as a Stack
# Using a list as a stack (Last In, First Out)
stack = []
stack.append(1)
stack.append(2)
popped_item = stack.pop() # Removes and returns the last item (2)
List as a Queue
from collections import deque
# Using a deque as a queue (First In, First Out)
queue = deque([1, 2, 3])
queue.append(4) # Adds 4 to the end
dequeued_item = queue.popleft() # Removes and returns the first item (1)
Conclusion
Mastering lists is essential for any Python developer. This cheat sheet provides a quick reference for creating, accessing, and manipulating lists. Whether you’re a beginner or an experienced programmer, having a solid understanding of Python lists will enhance your ability to work with data efficiently. Keep this cheat sheet handy to boost your productivity and write more Pythonic code. Happy coding!