Learn

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

Lists in Python

Lesson 16 Python 3.14 Runs in your browser Updated
In short

A list stores an ordered collection of values in one variable, written between square brackets. Items are read by index, starting at 0, and a slice such as items[1:3] gives a new list holding part of them. Lists can be changed after they are created, which sets them apart from strings and tuples.

Key facts

  • fruits = ["apple", "banana", "cherry"] creates a list of three strings. The square brackets make it a list.
  • The first item is fruits[0] and the last is fruits[-1]. Indexes start at 0.
  • fruits[1:3] gives a new list with the items at index 1 and 2. The stop index is never included.
  • A list can be changed in place, so fruits[1] = "kiwi" replaces an item. A string cannot.
  • len(fruits) returns the number of items, and "kiwi" in fruits tests whether a value is present.

What is a list in Python?

A list stores an ordered collection of values in one variable. You write the values between square brackets, separated by commas, and Python keeps them in that order. Each value is called an item, and a list is the everyday way to keep related values together, such as the names in a class or the prices in a cart.

Python
fruits = ["apple", "banana", "cherry"]
print(fruits)
print(type(fruits))
print(len(fruits))
Output
['apple', 'banana', 'cherry']
<class 'list'>
3

type() reports the value as a list, and len() counts its items. A list is a sequence, like a string, so the indexing and slicing you used on strings work the same way here. Unlike a string, a list can be changed after it is created, and the next lesson covers the methods that add and remove items.

How do I create a list in Python?

Write the items between square brackets. An empty pair of brackets makes an empty list, and one list can mix strings, numbers and booleans. list() builds a list from any iterable, such as a string or a range.

Python
empty = []
mixed = ["Ada", 36, True, 1.75]
letters = list("abc")
numbers = list(range(1, 6))
print(empty)
print(mixed)
print(letters)
print(numbers)
Output
[]
['Ada', 36, True, 1.75]
['a', 'b', 'c']
[1, 2, 3, 4, 5]

A list of one type is the common case, because a loop over it can treat every item the same way. The mixed list is legal, and it shows that a list holds values of any type. list("abc") splits the string into one item per character, and list(range(1, 6)) spells out the numbers a range would produce.

How do I access an item in a list by its index?

Put the item's position in square brackets after the list name. Positions are called indexes, or indices in Python's own messages. They start at 0, and a negative index counts from the end, so -1 is the last item.

Python
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[2])
print(fruits[-1])
print(fruits[-3])
Output
apple
cherry
cherry
apple

A list of three items has the indexes 0, 1 and 2, and the same items as -3, -2 and -1. Asking for index 3 stops the program with IndexError: list index out of range, the list error you will see most. The index has to be an integer, so fruits["0"] fails too.

How do I slice a list in Python?

Write a start and a stop index with a colon between them. A slice returns a new list holding the items from the start index up to, but not including, the stop index. Leave the start out to begin at the first item, leave the stop out to run to the end, and add a third number to set the step.

Python
nums = [10, 20, 30, 40, 50]
print(nums[1:3])
print(nums[:2])
print(nums[2:])
print(nums[::2])
print(nums[::-1])
print(nums)
Output
[20, 30]
[10, 20]
[30, 40, 50]
[10, 30, 50]
[50, 40, 30, 20, 10]
[10, 20, 30, 40, 50]

The last line proves the original list is untouched, because a slice always builds a new list. nums[::2] takes every second item, and nums[::-1] walks backward, which is the shortest way to reverse a list. The stop rule is the same one range() uses, so nums[1:3] holds two items, not three.

Python list slice forms
SliceMeaningExampleResult
items[start:stop]From start up to, but not including, stopnums[1:3][20, 30]
items[:stop]From the first item up to stopnums[:2][10, 20]
items[start:]From start to the endnums[2:][30, 40, 50]
items[::step]Every step-th item, so 2 takes every second one, and a negative step walks backwardnums[::-1][50, 40, 30, 20, 10]
items[:]Every item, as a new listnums[:][10, 20, 30, 40, 50]

How do I change an item in a list?

Assign a new value to the index. A list is mutable, which means it can be changed in place after it is created, so fruits[1] = "kiwi" replaces the second item without building a new list.

Python
fruits = ["apple", "banana", "cherry"]
fruits[1] = "kiwi"
print(fruits)
fruits[-1] = "mango"
print(fruits)
Output
['apple', 'kiwi', 'cherry']
['apple', 'kiwi', 'mango']

Strings don't allow this. Assigning to one character of a string raises a TypeError, because a string is immutable and every change to it produces a new string. Being mutable is the main difference between a list and a tuple, which the tuples lesson covers.

Python
word = "banana"
word[0] = "c"
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    word[0] = "c"
    ~~~~^^^
TypeError: 'str' object does not support item assignment

Methods such as append() and remove() add or remove items rather than replace them, and they get their own lesson next.

How do I get the length of a list or check whether it contains a value?

Call len() for the length and use in for the test. len(prices) returns the number of items, and 12 in prices is True when some item equals 12. A for loop visits the items one at a time.

Python
prices = [4.5, 12, 3.25]
print(len(prices))
print(12 in prices)
print(7 in prices)
total = 0
for price in prices:
    total = total + price
print(total)
Output
3
True
False
19.75

The loop adds up the prices the way the for loops lesson did, and sum(prices) does the same in one call. in compares values, not positions, so it can't tell you where the item is. The index() method does that, and the next lesson covers it.

What is a list of lists in Python?

A list of lists is a list whose items are themselves lists. It is also called a nested list, and it is the usual way to hold a grid or a table, with one inner list per row.

Python
grid = [[1, 2, 3], [4, 5, 6]]
print(grid[1])
print(grid[1][0])
print(len(grid))
for row in grid:
    print(row)
Output
[4, 5, 6]
4
2
[1, 2, 3]
[4, 5, 6]

grid[1] is the whole second row, and a second pair of brackets picks an item from it, so grid[1][0] is 4. len(grid) counts the rows, not every number, because the outer list has two items. Looping over the grid gives one row per pass.

Common mistakes with lists in Python

These four mistakes with lists are the common ones. Two stop the program with a message, and two run without complaint and give a wrong result.

  • IndexError: list index out of range. The index is too big, often by one, because the last item of a three-item list is at index 2, not 3. Check len(), or use -1 for the last item.
  • TypeError: list indices must be integers or slices, not str. The index was written as a string, such as fruits["0"], or came from input() without int() around it.
  • Changing a copy that isn't a copy. b = a makes both names point to the same list, so changing b changes a. Write b = a[:] to get a separate list, and the next lesson adds copy(), which does the same job.
  • Counting from 1. fruits[1] is the second item. The first is fruits[0].

Run the three programs to see the two messages and the shared list, then fix the first two in the editor.

Python
fruits = ["apple", "banana", "cherry"]
print(fruits[3])
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(fruits[3])
          ~~~~~~^^^
IndexError: list index out of range
Python
fruits = ["apple", "banana", "cherry"]
print(fruits["0"])
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(fruits["0"])
          ~~~~~~^^^^^
TypeError: list indices must be integers or slices, not str
Python
a = [1, 2, 3]
b = a
b[0] = 99
print(a)
c = a[:]
c[0] = 1
print(a)
print(c)
Output
[99, 2, 3]
[99, 2, 3]
[1, 2, 3]

Exercise

Change the last score from 64 to 70 by assigning to its index, so the program prints [72, 85, 90, 70], then 72, then 4. The starter prints the list unchanged.

Python
scores = [72, 85, 90, 64]
print(scores)
print(scores[0])
print(len(scores))
Output
Show the solution
scores = [72, 85, 90, 64]
scores[3] = 70
print(scores)
print(scores[0])
print(len(scores))

Quiz

This quiz has 5 questions. Pick an answer to see why it is right or wrong.

  1. 1What does this program print?

    fruits = ["apple", "banana", "cherry"]
    print(fruits[1])
  2. 2What does this program print?

    nums = [10, 20, 30, 40]
    print(nums[1:3])
  3. 3Which expression creates an empty list?

  4. 4What does this program print?

    nums = [3, 8, 5]
    print(nums[-1])
  5. 5What happens when a program runs print(fruits[3]) on a list of three items?

Frequently asked questions

What is a list in Python?
A list is an ordered collection of values stored in one variable, written between square brackets. Lists can hold any type, can be changed after creation, and are the most common way to keep several values together.
How do I create an empty list in Python?
Write a pair of square brackets, as in items = [], or call list() with no argument. Both give a list with no items that you can fill later with append().
What is the difference between list() and [] in Python?
Square brackets write a list directly, and list() builds one from a string, a range or another iterable. For an empty list the two are the same, and [] is the usual spelling.
What does [:] do to a Python list?
A slice with both ends left out, as in items[:], copies the whole list. Changing the copy leaves the original alone, which is not true after b = a.
What does an index of -1 mean in a Python list?
Negative indexes count from the end, so items[-1] is the last item and items[-2] is the one before it. They save you from writing items[len(items) - 1].
Can a Python list hold different data types?
Yes. One list can hold strings, numbers, booleans and even other lists at the same time, though most lists keep one type so a loop can treat every item the same way.
Is a Python list the same as an array?
No, but a list does the job an array does in other languages. A list grows and shrinks as needed and can mix types, while the array module that ships with Python holds one fixed type in less memory, and the NumPy library holds one fixed type and is much faster for large numeric data.