List Methods in Python
A list method is a function attached to a list that you call with a dot, such as fruits.append("kiwi"). Python lists have eleven methods, and they add, remove, sort, find and count items. Every one that changes the list does it in place and returns None, except pop(), which also hands back the item it removed.
Key facts
fruits.append("kiwi")adds one item to the end and returnsNone. The list itself changes.extend()adds every item of another list, andinsert(0, x)adds at the front.remove()deletes by value,pop()deletes by index and returns the item,deldeletes by index, andclear()empties the list.sort()reorders the list in place, andsorted()returns a new sorted list without touching the original.index()finds the position of a value, andcount()counts how often it appears.
What are list methods in Python?
A list method is a function attached to a list that you call with a dot. fruits.append("cherry") calls the append() method on the list named fruits, and the method changes that list in place. People also call them list functions, but the dot is what makes them methods, and the list before the dot is the one they work on.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
result = fruits.append("kiwi")
print(result)
print(fruits)['apple', 'banana', 'cherry'] None ['apple', 'banana', 'cherry', 'kiwi']
The second call shows the rule that trips up beginners. append() changes the list and returns None, so result holds nothing useful, and fruits = fruits.append("kiwi") would throw the list away. Call the method on its own line and print the list afterward.
Every other method in this lesson that changes a list follows the same rule and returns None. pop() is the one exception, because its job is to hand you the item it removes.
How do I add items to a list in Python?
Call append() to add one item at the end. insert(index, item) puts an item at a chosen position and shifts the rest along, and extend() adds every item of another list to the end. += with a list on the right does the same job as extend().
tasks = ["email", "lunch"]
tasks.insert(0, "standup")
print(tasks)
tasks.extend(["gym", "read"])
print(tasks)
tasks += ["sleep"]
print(tasks)['standup', 'email', 'lunch'] ['standup', 'email', 'lunch', 'gym', 'read'] ['standup', 'email', 'lunch', 'gym', 'read', 'sleep']
insert(0, "standup") puts the new task at the front, because index 0 is the first position. Adding to the end with append() is far more common, and it is how a for loop builds a list, one item per pass. The list comprehension lesson shows that loop next to its one-line form.
What is the difference between append() and extend()?
append() adds its argument as one item, and extend() adds each item inside its argument. Passing a list to append() nests it, so the list grows by one item that is itself a list.
a = [1, 2]
a.append([3, 4])
print(a)
print(len(a))
b = [1, 2]
b.extend([3, 4])
print(b)
print(len(b))[1, 2, [3, 4]] 3 [1, 2, 3, 4] 4
After append([3, 4]) the list has three items and the third is [3, 4]. After extend([3, 4]) it has four numbers. Pick extend() to join two lists and append() to add one value.
| Call | What it adds | Use it when |
|---|---|---|
a.append(x) | x as one item, whatever x is | You are adding one value |
a.extend(items) | Every item of items, one by one | You are joining another list, string or range onto the end |
How do I remove items from a list in Python?
Call remove() with the value, or pop() with the index. remove("green") deletes the first item equal to that value. pop() deletes the item at an index and returns it, taking the last item by default. del deletes by index without returning anything, and clear() empties the list.
colors = ["red", "green", "blue", "green"]
colors.remove("green")
print(colors)
last = colors.pop()
print(last)
print(colors)
del colors[0]
print(colors)
colors.clear()
print(colors)['red', 'blue', 'green'] green ['red', 'blue'] ['blue'] []
remove() took out only the first "green", and the second one stayed until pop() returned it. pop(0) takes the first item instead of the last. Removing a value that isn't there raises ValueError, so check with in first when you aren't sure.
| Form | What it removes | What it returns | Use it when |
|---|---|---|---|
a.remove(value) | The first item equal to value | Nothing, and it raises ValueError when the value is missing | You know the value, not the position |
a.pop(index) | The item at index, the last one by default | The removed item | You want to use the item you take out |
del a[index] | The item at index, or a slice such as a[1:3] | Nothing | You want it gone and don't need it back |
a.clear() | Every item | Nothing | You want to reuse an empty list |
How do I sort a list in Python?
Call sort() on the list. It reorders the items in place from smallest to largest, and sort(reverse=True) puts them from largest to smallest. Strings sort by their character codes, the number each character has in the Unicode table, so capital letters come before lowercase ones.
nums = [3, 1, 2]
nums.sort()
print(nums)
nums.sort(reverse=True)
print(nums)
names = ["Cy", "ada", "Bob"]
names.sort()
print(names)[1, 2, 3] [3, 2, 1] ['Bob', 'Cy', 'ada']
"Bob" and "Cy" sort before "ada" because every capital letter from A to Z has a lower code than every lowercase letter from a to z. Pass key=str.lower, written without parentheses, and sort() compares a lowercase copy of each string instead of the string itself.
names = ["Cy", "ada", "Bob"]
names.sort(key=str.lower)
print(names)['ada', 'Bob', 'Cy']
Sorting a list that mixes strings and numbers raises TypeError, because Python has no order between the two.
The built-in sorted() function is the other way to sort. It leaves the list alone and returns a new sorted list, which is what you want when the original order still matters.
nums = [3, 1, 2]
ordered = sorted(nums)
print(ordered)
print(nums)
print(nums.sort())[1, 2, 3] [3, 1, 2] None
The last line prints None, because sort() returns nothing, and printing its result is the mistake that makes people think sorting failed.
| Call | What it does | Use it when |
|---|---|---|
a.sort() | Reorders a in place and returns None | The original order is not needed again |
sorted(a) | Returns a new sorted list and leaves a unchanged | You need both orders, or the input is not a list |
How do I find and count items in a list?
Call index() for the position of a value and count() for how often it appears. index() returns the first match and raises ValueError when there is none, so test with in first. That leaves two of the eleven methods. reverse() flips the current order in place without sorting, and copy() returns a separate list with the same items.
letters = ["a", "b", "c", "b"]
print(letters.index("b"))
print(letters.count("b"))
print("z" in letters)
letters.reverse()
print(letters)
backup = letters.copy()
backup.append("d")
print(letters)
print(backup)1 2 False ['b', 'c', 'b', 'a'] ['b', 'c', 'b', 'a'] ['b', 'c', 'b', 'a', 'd']
Appending to the copy left the original alone, which is the point of copy(). Plain assignment, backup = letters, would have made two names for one list.
Which list methods does Python have?
Python lists have eleven methods, and the table lists all of them. Every method that changes the list returns None, except pop(), which returns the item it removed. Some jobs belong to built-in functions that take the list as an argument rather than to methods. You have met len(), sorted() and sum(), and min() and max() return the smallest and largest item.
| Method | What it does |
|---|---|
append(x) | Adds x to the end |
clear() | Removes every item |
copy() | Returns a new list with the same items |
count(x) | Returns how many items equal x |
extend(iterable) | Adds every item of the iterable to the end |
index(x) | Returns the index of the first item equal to x, or raises ValueError |
insert(i, x) | Inserts x at index i |
pop(i) | Removes and returns the item at index i, the last by default |
remove(x) | Removes the first item equal to x, or raises ValueError |
reverse() | Reverses the order in place |
sort() | Sorts in place, with reverse=True for descending order |
The table follows the list methods section of the official Python tutorial, which is the source to check when a detail matters.
Common mistakes with list methods in Python
These four mistakes with list methods are the common ones. Three stop the program with a message, and the first silently loses the list.
- Keeping the return value.
nums = nums.append(4)setsnumstoNone, becauseappend()returns nothing. Call the method on its own line. - TypeError: 'int' object is not iterable.
nums += 4tries to extend the list with the items of 4, and a number has none. Writenums.append(4)ornums += [4]. - ValueError: list.remove(x): x not in list.
remove()was given a value the list doesn't hold. Test withinfirst, or usepop()with an index you know exists. - TypeError: '<' not supported between instances of 'str' and 'int'.
sort()met a string and a number in the same list, and the two type names swap places depending on which items are compared first. Convert the items to one type before sorting.
Run the three broken programs to see the messages, then fix them in the editor.
nums = [1, 3, 2]
nums += 4Traceback (most recent call last):
File "main.py", line 2, in <module>
nums += 4
TypeError: 'int' object is not iterablenums = [1, 3, 2]
nums.remove(9)Traceback (most recent call last):
File "main.py", line 2, in <module>
nums.remove(9)
~~~~~~~~~~~^^^
ValueError: list.remove(x): x not in listnums = [3, "one", 2]
nums.sort()Traceback (most recent call last):
File "main.py", line 2, in <module>
nums.sort()
~~~~~~~~~^^
TypeError: '<' not supported between instances of 'str' and 'int'Exercise
Add "gym" to the end with append(), put "standup" at the front with insert(), and take "lunch" out with remove(), so the program prints ['standup', 'email', 'gym'] and then 3. The starter prints the list unchanged.
tasks = ["email", "lunch"]
print(tasks)
print(len(tasks))
['standup', 'email', 'gym'] 3
Show the solution
tasks = ["email", "lunch"]
tasks.append("gym")
tasks.insert(0, "standup")
tasks.remove("lunch")
print(tasks)
print(len(tasks))
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this program print?
nums = [3, 1, 2] nums.sort() print(nums)sort() reorders the list in place, so printing the list afterward shows it sorted. None would only appear if the program printed the result of the sort() call itself.
-
2What does this program print?
nums = [1, 2] print(nums.append(3))append() changes the list and returns None, and the program prints that return value rather than the list. The list itself now holds 1, 2 and 3.
-
3What does this program print?
a = [1, 2] a.append([3, 4]) print(len(a))append() adds its argument as one item, so the list becomes [1, 2, [3, 4]] with three items. extend() would have added 3 and 4 separately for a length of 4.
-
4Which call removes the value "b" from a list named letters when you do not know its position?
remove() searches for the value and deletes the first match. pop() and del take an index, not a value, and clear() takes no argument at all.
-
5What does this program print?
a = [3, 1] b = sorted(a) print(a, b)sorted() returns a new sorted list and leaves the original alone, so a keeps its order and b is sorted. Only sort() would have changed a.