0% found this document useful (0 votes)
7 views

python_list_cheatsheet

python related sheet pdf

Uploaded by

eagleblack872
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

python_list_cheatsheet

python related sheet pdf

Uploaded by

eagleblack872
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

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

for index, value in enumerate(my_list):


print(index, value) # (0, 1), (1, 3), (2, 4), (3, 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]

9. Sorting and Reversing

Before:
my_list = [5, 3, 8, 1]

Sorted:
my_list.sort() # [1, 3, 5, 8]

Reversed:
my_list.reverse() # [8, 5, 3, 1]

10. Copying a List

Before:
my_list = [1, 2, 3]
Copied:
new_list = my_list.copy() # [1, 2, 3]

11. List Functions

len(my_list) # Number of elements


min(my_list) # Smallest element
max(my_list) # Largest element
sum(my_list) # Sum of elements
my_list.index(50) # Index of first occurrence of 50
my_list.count(50) # Count occurrences of 50
my_list.clear() # Clear all elements

12. Nested Lists

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)

You might also like