Learn

Short lessons with real code you can edit and run on the page.

List Methods in Python

Lesson 17 Python 3.14 Runs in your browser Updated
In short

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 returns None. The list itself changes.
  • extend() adds every item of another list, and insert(0, x) adds at the front.
  • remove() deletes by value, pop() deletes by index and returns the item, del deletes by index, and clear() empties the list.
  • sort() reorders the list in place, and sorted() returns a new sorted list without touching the original.
  • index() finds the position of a value, and count() 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.

Python
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
result = fruits.append("kiwi")
print(result)
print(fruits)
Output
['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().

Python
tasks = ["email", "lunch"]
tasks.insert(0, "standup")
print(tasks)
tasks.extend(["gym", "read"])
print(tasks)
tasks += ["sleep"]
print(tasks)
Output
['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.

Python
a = [1, 2]
a.append([3, 4])
print(a)
print(len(a))
b = [1, 2]
b.extend([3, 4])
print(b)
print(len(b))
Output
[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.

Python append() compared with extend()
CallWhat it addsUse it when
a.append(x)x as one item, whatever x isYou are adding one value
a.extend(items)Every item of items, one by oneYou 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.

Python
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)
Output
['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.

Python remove(), pop(), del and clear() compared
FormWhat it removesWhat it returnsUse it when
a.remove(value)The first item equal to valueNothing, and it raises ValueError when the value is missingYou know the value, not the position
a.pop(index)The item at index, the last one by defaultThe removed itemYou want to use the item you take out
del a[index]The item at index, or a slice such as a[1:3]NothingYou want it gone and don't need it back
a.clear()Every itemNothingYou 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.

Python
nums = [3, 1, 2]
nums.sort()
print(nums)
nums.sort(reverse=True)
print(nums)
names = ["Cy", "ada", "Bob"]
names.sort()
print(names)
Output
[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.

Python
names = ["Cy", "ada", "Bob"]
names.sort(key=str.lower)
print(names)
Output
['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.

Python
nums = [3, 1, 2]
ordered = sorted(nums)
print(ordered)
print(nums)
print(nums.sort())
Output
[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.

Python sort() compared with sorted()
CallWhat it doesUse it when
a.sort()Reorders a in place and returns NoneThe original order is not needed again
sorted(a)Returns a new sorted list and leaves a unchangedYou 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.

Python
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)
Output
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.

Python list methods
MethodWhat 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) sets nums to None, because append() returns nothing. Call the method on its own line.
  • TypeError: 'int' object is not iterable. nums += 4 tries to extend the list with the items of 4, and a number has none. Write nums.append(4) or nums += [4].
  • ValueError: list.remove(x): x not in list. remove() was given a value the list doesn't hold. Test with in first, or use pop() 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.

Python
nums = [1, 3, 2]
nums += 4
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    nums += 4
TypeError: 'int' object is not iterable
Python
nums = [1, 3, 2]
nums.remove(9)
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    nums.remove(9)
    ~~~~~~~~~~~^^^
ValueError: list.remove(x): x not in list
Python
nums = [3, "one", 2]
nums.sort()
Output
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.

Python
tasks = ["email", "lunch"]
print(tasks)
print(len(tasks))
Output
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.

  1. 1What does this program print?

    nums = [3, 1, 2]
    nums.sort()
    print(nums)
  2. 2What does this program print?

    nums = [1, 2]
    print(nums.append(3))
  3. 3What does this program print?

    a = [1, 2]
    a.append([3, 4])
    print(len(a))
  4. 4Which call removes the value "b" from a list named letters when you do not know its position?

  5. 5What does this program print?

    a = [3, 1]
    b = sorted(a)
    print(a, b)

Frequently asked questions

What does append() do in Python?
append() adds one item to the end of a list and changes the list in place. It returns None, so call it on its own line rather than assigning its result back to the list.
What is the difference between append() and extend() in Python?
append() adds its argument as a single item, so appending a list nests it. extend() adds each item of its argument one by one, which is what you want when joining two lists.
What is the difference between sort() and sorted() in Python?
sort() reorders the list in place and returns None. sorted() leaves the list alone and returns a new sorted list, and it works on any iterable, not only lists.
How do I remove an item from a list by its value?
Call remove() with the value, as in colors.remove('green'). It deletes the first match only and raises a ValueError when the value is not in the list, so test with in first when you are not sure.
What does pop() return in Python?
pop() removes an item and returns it, so you can keep what was removed. With no argument it takes the last item, and pop(0) takes the first.
Does append() return the new list?
No. append() returns None and changes the list it was called on, so print the list itself after the call to see the result.
How do I add several items to a list at once?
Call extend() with a list of the items, or use += with a list on the right. Both add every item to the end, while append() with a list would add the whole list as one item.