Python List functions
Here’s a comprehensive list of the built-in list methods in Python, along with a brief description of each:
List Methods in Python
list.append(x)
- Adds an item
x
to the end of the list.
- Adds an item
list.extend(iterable)
- Extends the list by appending elements from an iterable (e.g., another list).
list.insert(i, x)
- Inserts an item
x
at a given positioni
in the list.
- Inserts an item
list.remove(x)
- Removes the first occurrence of an item
x
from the list. Raises aValueError
if the item is not found.
- Removes the first occurrence of an item
list.pop([i])
- Removes and returns the item at the given position
i
. If no index is specified,pop()
removes and returns the last item in the list.
- Removes and returns the item at the given position
list.clear()
- Removes all items from the list.
list.index(x[, start[, end]])
- Returns the index of the first occurrence of an item
x
in the list. Raises aValueError
if the item is not found. You can also specify astart
andend
index for searching.
- Returns the index of the first occurrence of an item
list.count(x)
- Returns the number of occurrences of an item
x
in the list.
- Returns the number of occurrences of an item
list.sort(key=None, reverse=False)
- Sorts the items of the list in place (the arguments can be used for custom sorting).
list.reverse()
- Reverses the elements of the list in place.
list.copy()
- Returns a shallow copy of the list.
Example Usage of List Methods
Here’s a brief example demonstrating some of these methods:
Summary
These methods provide a rich set of functionalities for manipulating lists in Python, making it easy to add, remove, and modify elements within a list.