A list stores many values in one variable, in a fixed order, and you can change it after you create it. Lists are the most used collection in Python. This lesson covers how to create, index, slice, change and loop through lists, and every common list method with its output.

Try every example in our online Python compiler.

What is a list?

A list is an ordered, changeable collection. It is written with square brackets [], and the items are separated by commas. A list can hold any type of value, and the same value can appear more than once.

Create a list

fruits = ['apple', 'banana', 'cherry']
mixed = [1, 'two', 3.5, True]
empty = []

print(fruits)
print(type(fruits))
print(mixed)
print(list('abc'))
print(list(range(5)))

Output:

['apple', 'banana', 'cherry']
<class 'list'>
[1, 'two', 3.5, True]
['a', 'b', 'c']
[0, 1, 2, 3, 4]

Access items by index

Every item has a position called an index. Counting starts at 0 from the left. Negative indexes count from the end, so -1 is the last item.

Item

apple

banana

cherry

Index

0

1

2

Negative index

-3

-2

-1

fruits = ['apple', 'banana', 'cherry']
print(fruits[0])
print(fruits[2])
print(fruits[-1])
print(fruits[-2])

Output:

apple
cherry
cherry
banana

Slicing a list

Use list[start:stop:step] to get part of a list. The start index is included, and the stop index is not.

numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4])
print(numbers[:3])
print(numbers[3:])
print(numbers[-3:])
print(numbers[::2])
print(numbers[::-1])

Output:

[20, 30, 40]
[10, 20, 30]
[40, 50, 60]
[40, 50, 60]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]

The last line uses a step of -1, which reverses the list.

Change items

Lists are mutable, which means you can change them in place.

fruits = ['apple', 'banana', 'cherry']
fruits[1] = 'mango'
print(fruits)

fruits[0:2] = ['kiwi', 'grape']
print(fruits)

Output:

['apple', 'mango', 'cherry']
['kiwi', 'grape', 'cherry']

List methods

Method

What it does

append(x)

Adds one item at the end

extend(items)

Adds many items at the end

insert(i, x)

Inserts an item at index i

remove(x)

Removes the first item equal to x

pop(i)

Removes and returns the item at index i (the last item if i is not given)

del list[i]

Deletes the item at index i

clear()

Removes all items

index(x)

Returns the index of the first x

count(x)

Counts how many times x appears

sort()

Sorts the list in place

reverse()

Reverses the list in place

copy()

Returns a copy of the list

Add items

colors = ['red', 'green']
colors.append('blue')
print(colors)

colors.extend(['pink', 'black'])
print(colors)

colors.insert(1, 'white')
print(colors)

Output:

['red', 'green', 'blue']
['red', 'green', 'blue', 'pink', 'black']
['red', 'white', 'green', 'blue', 'pink', 'black']

Remove items

colors = ['red', 'white', 'green', 'blue', 'pink', 'black']

colors.remove('green')
print(colors)

last = colors.pop()
print(last, colors)

first = colors.pop(0)
print(first, colors)

del colors[0]
print(colors)

colors.clear()
print(colors)

Output:

['red', 'white', 'blue', 'pink', 'black']
black ['red', 'white', 'blue', 'pink']
red ['white', 'blue', 'pink']
['blue', 'pink']
[]

Find, count and measure

nums = [5, 2, 9, 2, 7]
print(nums.index(9))
print(nums.count(2))
print(len(nums), max(nums), min(nums), sum(nums))

Output:

2
2
5 9 2 25

len() gives the number of items, max() and min() give the largest and smallest, and sum() adds up a list of numbers.

Sort and reverse

nums = [5, 2, 9, 2, 7]
nums.sort()
print(nums)

nums.sort(reverse=True)
print(nums)

nums.reverse()
print(nums)

original = [3, 1, 2]
new_list = sorted(original)
print(original, new_list)

Output:

[2, 2, 5, 7, 9]
[9, 7, 5, 2, 2]
[2, 2, 5, 7, 9]
[3, 1, 2] [1, 2, 3]

sort() changes the list itself. sorted() leaves the original alone and returns a new sorted list.

Loop through a list

fruits = ['apple', 'banana']

for fruit in fruits:
    print(fruit)

for i, fruit in enumerate(fruits):
    print(i, fruit)

Output:

apple
banana
0 apple
1 banana

Use enumerate() when you need the index as well as the item.

Check if an item is in a list

fruits = ['apple', 'banana']
print('apple' in fruits)
print('grape' in fruits)

Output:

True
False

Nested lists

A list can contain other lists. This is how you store rows and columns, like a table.

matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix[1][2])
print(matrix[0])

for row in matrix:
    print(row)

Output:

6
[1, 2, 3]
[1, 2, 3]
[4, 5, 6]

matrix[1][2] means row 1, column 2, which is 6.

Join and repeat lists

l1 = [1, 2]
l2 = [3]
print(l1 + l2)
print([0] * 3)

Output:

[1, 2, 3]
[0, 0, 0]

Copy a list correctly

Writing b = a does not copy the list. Both names point to the same list, so a change through one shows up in the other. Use copy() to get a separate list.

a = [1, 2, 3]
b = a
b.append(4)
print(a)

c = a.copy()
c.append(5)
print(a, c)

Output:

[1, 2, 3, 4]
[1, 2, 3, 4] [1, 2, 3, 4, 5]

List comprehension (a short way to build a list)

squares = [x * x for x in range(1, 6)]
print(squares)

Output:

[1, 4, 9, 16, 25]

You will learn this in detail in the lesson on list comprehension.

Common mistakes

1. Using an index that does not exist.

print([1, 2, 3][5])
IndexError: list index out of range

2. Removing an item that is not in the list.

[1, 2].remove(9)
ValueError: list.remove(x): x not in list

3. Saving the result of sort(). sort() changes the list and returns None.

result = [3, 1, 2].sort()
print(result)
None

Practice questions

  1. For nums = [4, 8, 15, 16, 23, 42], what are nums[2], nums[-1] and nums[1:4]?
  2. Remove the last item of [1, 2, 3, 4, 5] and insert 99 at the start.
  3. Sort the list [‘b’, ‘a’, ‘c’] in ascending order.
  4. Find the average of [1, 2, 3, 4, 5, 6], and print the list in reverse.
  5. Find the largest item of [3, 8, 1, 9] and its index.

Answers

nums = [4, 8, 15, 16, 23, 42]
print(nums[2], nums[-1], nums[1:4])      # 15 42 [8, 15, 16]

q2 = [1, 2, 3, 4, 5]
q2.pop()
q2.insert(0, 99)
print(q2)                                # [99, 1, 2, 3, 4]

q3 = ['b', 'a', 'c']
q3.sort()
print(q3)                                # ['a', 'b', 'c']

q4 = [1, 2, 3, 4, 5, 6]
print(sum(q4) / len(q4))                 # 3.5
print(q4[::-1])                          # [6, 5, 4, 3, 2, 1]

q5 = [3, 8, 1, 9]
print(max(q5), q5.index(max(q5)))        # 9 3

Summary

  • A list is an ordered, changeable collection written in [].
  • Indexes start at 0, and negative indexes count from the end.
  • Use slicing to get part of a list, and methods like append(), insert(), remove() and pop() to change it.
  • Use copy() when you need an independent copy.