python_list_cheatsheet
python_list_cheatsheet
This Python List Cheatsheet covers list creation, modifications, access, and all essential functions.
It's designed to help you while working on small and large projects involving Python lists.
1. Creating a List
Before:
my_list = [] # Empty list
After:
my_list = [1, 2, 3] # List with elements
2. Accessing Elements
Before:
my_list = [10, 20, 30]
Accessing:
my_list[0] # 10
my_list[-1] # 30
3. Slicing
Before:
my_list = [1, 2, 3, 4, 5]
After Slicing:
my_list[1:3] # [2, 3]
my_list[::2] # [1, 3, 5]
4. Modifying a List
Before:
my_list = [1, 2, 3]
After Modifying:
my_list[1] = 100 # [1, 100, 3]
my_list.append(4) # [1, 100, 3, 4]
my_list.extend([5, 6]) # [1, 100, 3, 4, 5, 6]
my_list.insert(1, 50) # [1, 50, 100, 3, 4, 5, 6]
5. Removing Elements
Before:
my_list = [1, 50, 100, 3, 4, 5, 6]
After Removing:
my_list.remove(100) # [1, 50, 3, 4, 5, 6]
del my_list[1] # [1, 3, 4, 5, 6]
my_list.pop() # [1, 3, 4, 5]
6. Membership Check
Before:
my_list = [1, 3, 4, 5]
Check if 5 is in list:
50 in my_list # False
7. Iteration
Before:
my_list = [1, 3, 4, 5]
Looping:
for item in my_list:
print(item) # 1, 3, 4, 5
8. List Comprehension
Before:
squares = [x**2 for x in range(5)]
Output:
[0, 1, 4, 9, 16]
Filtered List:
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
Before:
my_list = [5, 3, 8, 1]
Sorted:
my_list.sort() # [1, 3, 5, 8]
Reversed:
my_list.reverse() # [8, 5, 3, 1]
Before:
my_list = [1, 2, 3]
Copied:
new_list = my_list.copy() # [1, 2, 3]
Before:
matrix = [[1, 2], [3, 4]]
Access Element:
matrix[0][1] # 2
13. Enumerate
Before:
my_list = [1, 2, 3]
After Enumerate:
for index, value in enumerate(my_list):
print(index, value) # (0, 1), (1, 2), (2, 3)