Python Lists Cheat Sheet
1. Creating Lists
1.1 Empty List
= [] my_list
1.2 List with Elements
= [1, 2, 3, 4, 5] my_list
1.3 List with Mixed Data Types
= [1, "hello", 3.14, True] mixed_list
1.4 List of Lists (Nested Lists)
= [[1, 2, 3], [4, 5, 6], [7, 8, 9]] nested_list
2. Accessing Elements
2.1 Access by Index (0-based)
= [10, 20, 30, 40]
my_list print(my_list[0]) # Output: 10
print(my_list[2]) # Output: 30
2.2 Access Last Element
print(my_list[-1]) # Output: 40
2.3 Slicing a List
= my_list[1:3] # Output: [20, 30] sublist
3. Modifying Lists
3.1 Change Element by Index
1] = 25 # my_list becomes [10, 25, 30, 40] my_list[
3.2 Append an Element
50) # my_list becomes [10, 25, 30, 40, 50] my_list.append(
3.3 Insert an Element at a Specific Position
1, 15) # my_list becomes [10, 15, 25, 30, 40, 50] my_list.insert(
3.4 Extend List with Another List
60, 70]) # my_list becomes [10, 15, 25, 30, 40, 50, 60, 70] my_list.extend([
4. Removing Elements
4.1 Remove by Value
25) # my_list becomes [10, 15, 30, 40, 50, 60, 70] my_list.remove(
4.2 Remove by Index
del my_list[0] # my_list becomes [15, 30, 40, 50, 60, 70]
4.3 Pop Last Element
= my_list.pop() # my_list becomes [15, 30, 40, 50, 60] last_element
4.4 Pop by Index
= my_list.pop(2) # my_list becomes [15, 30, 50, 60] element
5. List Operations
5.1 Length of List
= len(my_list) # Output: 4 length
5.2 Check if Element Exists
= 30 in my_list # Output: True is_in_list
5.3 Concatenate Two Lists
= my_list + [80, 90] # Output: [15, 30, 50, 60, 80, 90] combined_list
5.4 Repeat a List
= [1, 2, 3] * 3 # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3] repeated_list
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
= [x**2 for x in range(5)] # Output: [0, 1, 4, 9, 16] squares
7.2 List Comprehension with Condition
= [x for x in range(10) if x % 2 == 0] # Output: [0, 2, 4, 6, 8] evens
8. List Methods
8.1 Sort a List
# Sorts in place my_list.sort()
8.2 Sorted Copy of List
= sorted(my_list) # Returns a sorted copy sorted_list
8.3 Reverse a List
# Reverses in place my_list.reverse()
8.4 Count Occurrences of an Element
= my_list.count(30) # Output: 1 count
8.5 Find Index of an Element
= my_list.index(50) # Output: 2 index
9. 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)