Python List Operations and Examples
1. Append to a List
my_list = [1, 2, 3]
my_list.append(4)
print("After append:", my_list)
2. Insert into a List
my_list = [1, 2, 4]
my_list.insert(2, 3)
print("After insert:", my_list)
3. Remove from a List
my_list = [1, 2, 3, 4]
my_list.remove(3)
print("After remove:", my_list)
4. Pop from a List
my_list = [1, 2, 3, 4]
popped_element = my_list.pop()
print("Popped element:", popped_element)
print("After pop:", my_list)
5. Clear a List
my_list = [1, 2, 3, 4]
my_list.clear()
print("After clear:", my_list)
6. List Index and Count
my_list = [1, 2, 3, 2, 4, 2]
index_of_3 = my_list.index(3)
count_of_2 = my_list.count(2)
print("Index of 3:", index_of_3)
print("Count of 2:", count_of_2)
7. Sorting a List
my_list = [4, 2, 3, 1]
my_list.sort()
print("Sorted list:", my_list)
8. Reverse a List
my_list = [1, 2, 3, 4]
my_list.reverse()
print("Reversed list:", my_list)
9. List Slicing
my_list = [10, 20, 30, 40, 50]
print("Sliced list [1:4]:", my_list[1:4])
print("Sliced list with step [::2]:", my_list[::2])
10. List Comprehension
squares = [x**2 for x in range(1, 6)]
print("Squares using list comprehension:", squares)
11. Copying a List
original = [1, 2, 3]
copy_list = original.copy()
copy_list.append(4)
print("Original list:", original)
print("Copied list:", copy_list)
12. Joining Two Lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
joined_list = list1 + list2
print("Joined list:", joined_list)
13. Nested Lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Matrix:")
for row in matrix:
print(row)
14. List Membership Check
my_list = ['apple', 'banana', 'cherry']
item = 'banana'
if item in my_list:
print(item, "is in the list.")
else:
print(item, "is not in the list.")
15. List Length
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print("Length of the list:", length)