List Handing Methods
append() Adds an element at the end of the list
In [1]: my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
[1, 2, 3, 4]
clear() Removes all the elements from the list
In [2]: my_list = [1, 2, 3]
my_list.clear()
print(my_list)
[]
copy() Returns a copy of the list
In [3]: original_list = [1, 2, 3, 4]
copied_list = original_list.copy()
print("Original List:", original_list) # Output: [1, 2, 3, 4]
print("Copied List:", copied_list) # Output: [1, 2, 3, 4]
copied_list.append(5)
print("Modified Copied List:", copied_list) # Output: [1, 2, 3, 4, 5]
print("Original List after modification:", original_list) # Output: [1, 2, 3, 4]
Original List: [1, 2, 3, 4]
Copied List: [1, 2, 3, 4]
Modified Copied List: [1, 2, 3, 4, 5]
Original List after modification: [1, 2, 3, 4]
count() Returns the number of elements with the specified value
In [4]: my_list = [1, 2, 3, 2]
count = my_list.count(2)
print(count)
extend() Add the elements of a list (or any iterable), to the end of the current list
In [5]: my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list)
[1, 2, 3, 4, 5]
index() Returns the index of the first element with the specified value
In [6]: my_list = [1, 2, 3, 2]
index = my_list.index(2)
print(index)
insert() Adds an element at the specified position
In [7]: my_list = [1, 2, 3]
my_list.insert(1, 1.5)
print(my_list)
[1, 1.5, 2, 3]
pop() Removes the element at the specified position
In [8]: my_list = [1, 2, 3]
element = my_list.pop(1)
print(element) # Output: 2
print(my_list)
2
[1, 3]
remove() Removes the item with the specified value
In [9]: my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list)
[1, 3, 2]
reverse() Reverses the order of the list
In [10]: my_list = [1, 2, 3]
my_list.reverse()
print(my_list)
[3, 2, 1]
sort() Sorts the list
In [11]: my_list = [3, 1, 2]
my_list.sort()
print(my_list)
[1, 2, 3]
In [12]: my_list = [1, 2, 3]
# Append
my_list.append(4)
print("After append:", my_list)
# Extend
my_list.extend([5, 6])
print("After extend:", my_list)
# Insert
my_list.insert(3, 3.5)
print("After insert:", my_list)
# Remove
my_list.remove(3)
print("After remove:", my_list)
# Pop
popped_element = my_list.pop()
print("Popped element:", popped_element)
print("After pop:", my_list)
# Clear
my_list.clear()
print("After clear:", my_list)
# Index
my_list = [1, 2, 3, 2]
index = my_list.index(2)
print("Index of 2:", index)
# Count
count = my_list.count(2)
print("Count of 2:", count)
# Sort
my_list = [3, 1, 2]
my_list.sort()
print("Sorted list:", my_list)
# Reverse
my_list.reverse()
print("Reversed list:", my_list)
After append: [1, 2, 3, 4]
After extend: [1, 2, 3, 4, 5, 6]
After insert: [1, 2, 3, 3.5, 4, 5, 6]
After remove: [1, 2, 3.5, 4, 5, 6]
Popped element: 6
After pop: [1, 2, 3.5, 4, 5]
After clear: []
Index of 2: 1
Count of 2: 2
Sorted list: [1, 2, 3]
Reversed list: [3, 2, 1]
In [ ]: