Python Lists Cheat Sheet
1. Creating Lists
1.1 Empty List
my_list = []1.2 List with Elements
my_list = [1, 2, 3, 4, 5]1.3 List with Mixed Data Types
mixed_list = [1, "hello", 3.14, True]1.4 List of Lists (Nested Lists)
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]2. Accessing Elements
2.1 Access by Index (0-based)
my_list = [10, 20, 30, 40]
print(my_list[0]) # Output: 10
print(my_list[2]) # Output: 302.2 Access Last Element
print(my_list[-1]) # Output: 402.3 Slicing a List
sublist = my_list[1:3] # Output: [20, 30]3. Modifying Lists
3.1 Change Element by Index
my_list[1] = 25 # my_list becomes [10, 25, 30, 40]3.2 Append an Element
my_list.append(50) # my_list becomes [10, 25, 30, 40, 50]3.3 Insert an Element at a Specific Position
my_list.insert(1, 15) # my_list becomes [10, 15, 25, 30, 40, 50]3.4 Extend List with Another List
my_list.extend([60, 70]) # my_list becomes [10, 15, 25, 30, 40, 50, 60, 70]4. Removing Elements
4.1 Remove by Value
my_list.remove(25) # my_list becomes [10, 15, 30, 40, 50, 60, 70]4.2 Remove by Index
del my_list[0] # my_list becomes [15, 30, 40, 50, 60, 70]4.3 Pop Last Element
last_element = my_list.pop() # my_list becomes [15, 30, 40, 50, 60]4.4 Pop by Index
element = my_list.pop(2) # my_list becomes [15, 30, 50, 60]5. List Operations
5.1 Length of List
length = len(my_list) # Output: 45.2 Check if Element Exists
is_in_list = 30 in my_list # Output: True5.3 Concatenate Two Lists
combined_list = my_list + [80, 90] # Output: [15, 30, 50, 60, 80, 90]5.4 Repeat a List
repeated_list = [1, 2, 3] * 3 # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]6. Looping Through Lists
6.1 Using a for Loop
for item in my_list:
print(item)6.2 Using enumerate for Index and Value
for index, value in enumerate(my_list):
print(f"Index {index} has value {value}")7. List Comprehensions
7.1 Basic List Comprehension
squares = [x**2 for x in range(5)] # Output: [0, 1, 4, 9, 16]7.2 List Comprehension with Condition
evens = [x for x in range(10) if x % 2 == 0] # Output: [0, 2, 4, 6, 8]8. List Methods
8.1 Sort a List
my_list.sort() # Sorts in place8.2 Sorted Copy of List
sorted_list = sorted(my_list) # Returns a sorted copy8.3 Reverse a List
my_list.reverse() # Reverses in place8.4 Count Occurrences of an Element
count = my_list.count(30) # Output: 18.5 Find Index of an Element
index = my_list.index(50) # Output: 29. Common List Pitfalls
9.1 Avoid Modifying a List While Iterating
# Incorrect
for item in my_list:
if item < 20:
my_list.remove(item)
# Correct (Using a copy)
for item in my_list[:]:
if item < 20:
my_list.remove(item)