Python List Methods with examples
Python List Methods with Examples
Below are the common Python list methods along with explanations and examples for each.
- append(x): Adds an item 'x' to the end of the list.
# Example:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
extend(iterable): Adds all the elements of an iterable (like another list) to the end of the list.
# Example:
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
insert(i, x): Inserts an item 'x' at the specified index 'i'.
# Example:
my_list = [1, 2, 3]
my_list.insert(1, 4) # Insert 4 at index 1
print(my_list) # Output: [1, 4, 2, 3]
remove(x): Removes the first occurrence of item 'x' from the list.
# Example:
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
pop([i]): Removes and returns the item at the given index 'i'. If no index is provided, it removes and returns the last item.
# Example:
my_list = [1, 2, 3]
removed_item = my_list.pop(1) # Removes and returns the item at index 1
print(removed_item) # Output: 2
print(my_list) # Output: [1, 3]
clear(): Removes all items from the list.
# Example:
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
index(x[, start[, end]]): Returns the index of the first occurrence of item 'x' within the list. You can specify the start and end indices for searching.
# Example:
my_list = [1, 2, 3, 2]
index_of_2 = my_list.index(2) # Finds the first occurrence of 2
print(index_of_2) # Output: 1
count(x): Returns the number of occurrences of item 'x' in the list.
# Example:
my_list = [1, 2, 2, 3]
count_of_2 = my_list.count(2)
print(count_of_2) # Output: 2
sort(reverse=False, key=None): Sorts the items of the list in ascending order by default. You can set reverse=True to sort in descending order.
# Example:
my_list = [3, 1, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3]
# Example with reverse=True:
my_list.sort(reverse=True)
print(my_list) # Output: [3, 2, 1]
reverse(): Reverses the order of items in the list.
# Example:
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
copy(): Returns a shallow copy of the list.
# Example:
my_list = [1, 2, 3]
my_list_copy = my_list.copy()
print(my_list_copy) # Output: [1, 2, 3]