Here’s are some of the most commonly used list methods in Python:
append(item)
: Adds an item to the end of the list.extend(iterable)
: Adds all the elements of an iterable (like list, tuple, string etc.) to the end of the list.insert(index, item)
: Inserts an item at a specific position in the list.remove(item)
: Removes the first occurrence of the item from the list.pop(index)
: Removes and returns the item at the given index. If no index is specified, it removes and returns the last item in the list.index(item)
: Returns the index of the first occurrence of the item in the list.count(item)
: Returns the number of times the item appears in the list.sort()
: Sorts the items in the list in ascending order.reverse()
: Reverses the order of the items in the list.clear()
: Removes all items from the list.
Here’s an example of how you might use some of these methods:
# Create a list
numbers = [1, 2, 3, 4, 5]
# Append a number to the list
numbers.append(6)
# Extend the list with another list
numbers.extend([7, 8, 9])
# Insert a number at a specific position
numbers.insert(0, 0)
# Remove the first occurrence of a number
numbers.remove(0)
# Pop the last number from the list
last_number = numbers.pop()
# Get the index of a number
index_of_five = numbers.index(5)
# Count the occurrences of a number
count_of_five = numbers.count(5)
# Sort the numbers
numbers.sort()
# Reverse the numbers
numbers.reverse()
# Clear the list
numbers.clear()