List methods¶
This reference documents all methods available on Python list objects and the built-in functions commonly used with lists.
append()¶
Add an item to the end of the list. Modifies the list in place and returns None.
clear()¶
Remove all items from the list, leaving it empty.
copy()¶
Return a shallow copy of the list. Changes to the copy do not affect the original.
count()¶
Return the number of times a value appears in the list.
extend()¶
Add all items from an iterable to the end of the list. This is equivalent to list += iterable.
fruits = ["apple", "banana"]
fruits.extend(["cherry", "date"])
# fruits is now ["apple", "banana", "cherry", "date"]
index()¶
Return the index of the first occurrence of a value. Raises ValueError if the value is not found.
| Parameter | Description |
|---|---|
value |
The value to search for |
start |
Optional start index for the search |
stop |
Optional stop index for the search |
insert()¶
Insert an item at the given index. Items at and after the index are shifted to the right.
fruits = ["apple", "cherry"]
fruits.insert(1, "banana")
# fruits is now ["apple", "banana", "cherry"]
pop()¶
Remove and return the item at the given index. If no index is specified, removes and returns the last item. Raises IndexError if the list is empty or the index is out of range.
fruits = ["apple", "banana", "cherry"]
last = fruits.pop() # "cherry"
first = fruits.pop(0) # "apple"
remove()¶
Remove the first occurrence of a value from the list. Raises ValueError if the value is not found.
reverse()¶
Reverse the items of the list in place.
sort()¶
Sort the list in place. Returns None.
| Parameter | Description |
|---|---|
key |
A function that extracts a comparison key from each item |
reverse |
If True, sort in descending order |
numbers = [3, 1, 4, 1, 5]
numbers.sort()
# numbers is now [1, 1, 3, 4, 5]
words = ["banana", "apple", "cherry"]
words.sort(key=len)
# words is now ["apple", "banana", "cherry"]
Built-in functions for lists¶
len()¶
Return the number of items in the list.
min() and max()¶
Return the smallest or largest item in the list.
sum()¶
Return the sum of all items in the list.
sorted()¶
Return a new sorted list without modifying the original. Accepts the same key and reverse parameters as sort().
reversed()¶
Return a reverse iterator. Use list() to convert it to a list.
enumerate()¶
Return an iterator of (index, item) pairs.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
zip()¶
Combine items from multiple lists into tuples.