Lists in Python

Published by Brayan K

Store and manage multiple values in a single variable using Python lists.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A list holds several values, in order

A list is written as values inside square brackets, separated by commas. It keeps them in the order you wrote them, it can hold the same value more than once, and its values can be of different types. len() counts them:

scores = [72, 91, 58, 91]
names = ["Ada", "Grace"]
mixed = ["Ada", 36, True]
empty = []

print(scores)
print(names)
print(len(scores), len(mixed), len(empty))

# ✅ Expected output:
# [72, 91, 58, 91]
# ['Ada', 'Grace']
# 4 3 0

A printed list looks the way you would type it. Text in it shows in quotes, which Python makes single unless the text itself holds an apostrophe, as in ["don't", 'stop']. len() is a built-in function, like print(), so you write len(scores); scores.len() stops with AttributeError: 'list' object has no attribute 'len'. The functions that belong to a list, called with a dot after it, are its methods, and most of this lesson is about them.

Positions start at 0

Each item has a position, its index. The first item is at index 0, so the last of four is at index 3. Negative indexes count from the end, starting at -1:

Item"apple""banana""cherry""date"
Index0123
From the end-4-3-2-1

Put the index in square brackets after the list to get that item:

fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0], fruits[1])
print(fruits[-1], fruits[-2])
print(fruits[len(fruits) - 1])

# ✅ Expected output:
# apple banana
# date cherry
# date

fruits[-1] is the last item however long the list is, a shorter way to write fruits[len(fruits) - 1]. Ask for a position the list doesn't have and the program stops. Four items have indexes 0 to 3, so 4 is one past the end, the usual way to get this error:

fruits = ["apple", "banana", "cherry", "date"]
print(fruits[4])

# ✅ Expected error:
# IndexError: list index out of range

An index also has to be a whole number. nums[len(nums) / 2], to get a middle item, stops with TypeError: list indices must be integers or slices, not float, because / always gives a float; use // from Operators and Expressions.

Changing an item

Assigning to an index replaces the item there:

colors = ["red", "green", "blue"]
colors[0] = "yellow"
colors[-1] = "purple"
print(colors)

# ✅ Expected output:
# ['yellow', 'green', 'purple']

Assignment only replaces; it can't make the list longer. A position past the end fails with a message of its own:

colors = ["red", "green", "blue"]
colors[3] = "black"

# ✅ Expected error:
# IndexError: list assignment index out of range

Text can't be changed this way at all: word[0] = "b" on a string stops with TypeError: 'str' object does not support item assignment. That's the difference Variables and Data Types pointed out: a list can be changed in place, while numbers and text can only be replaced.

Adding items: append, insert and extend

Three methods add to a list. Each changes the list it's called on:

cart = ["milk"]
cart.append("bread")
cart.insert(0, "tea")
cart.extend(["eggs", "jam"])
print(cart)

# ✅ Expected output:
# ['tea', 'milk', 'bread', 'eggs', 'jam']

append() adds one item at the end. insert(0, "tea") puts "tea" at index 0 and moves every item after it one place right. extend() adds each item of another list at the end. The difference between the first and the last matters: append() adds whatever you give it as a single item, even a list.

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

b = [1, 2]
b.extend([3, 4])
print(b, len(b))

# ✅ Expected output:
# [1, 2, [3, 4]] 3
# [1, 2, 3, 4] 4

extend() goes through what you give it one item at a time, as a for loop does. Python calls a value it can go through like that iterable, and a single number isn't one:

nums = [1, 2]
nums.extend(5)

# ✅ Expected error:
# TypeError: 'int' object is not iterable

Two more mistakes give errors that say what's wrong. nums.append(3, 4) stops with TypeError: list.append() takes exactly one argument (2 given), and nums.push(3), the name other languages use, stops with AttributeError: 'list' object has no attribute 'push'. + joins two lists into a new one and leaves both alone, but both sides must be lists: nums + 3 stops with TypeError: can only concatenate list (not "int") to list.

Removing items: remove, pop and del

remove() deletes by value. pop() and del delete by position:

queue = ["Ada", "Linus", "Grace", "Linus"]
queue.remove("Linus")
print(queue)

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

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

del queue[0]
print(queue)

# ✅ Expected output:
# ['Ada', 'Grace', 'Linus']
# Linus ['Ada', 'Grace']
# Ada ['Grace']
# []

remove() deletes only the first match, so the second "Linus" stayed until pop() took it. pop() hands back the item it removes: the last one, or the one at the index you give. del deletes the item at an index and gives nothing back. Removing a value that isn't there stops the program:

queue = ["Ada", "Grace"]
queue.remove("Linus")

# ✅ Expected error:
# ValueError: list.remove(x): x not in list

The message doesn't say which value was missing. And there's nothing to pop from an empty list:

queue = []
queue.pop()

# ✅ Expected error:
# IndexError: pop from empty list

To avoid both, check first: if name in queue: before removing, and if queue: before popping, since an empty list counts as false. Three ways to ask about values: in asks whether a value is in the list, count() how many times, and index() where the first one is:

letters = ["a", "b", "a", "c"]
print("a" in letters, "z" in letters)
print(letters.count("a"))
print(letters.index("c"))

# ✅ Expected output:
# True False
# 2
# 3

Like remove(), index() fails on a value that isn't there: letters.index("z") stops with ValueError: 'z' is not in list, which names the value. Python 3.14 words it like remove()'s, ValueError: list.index(x): x not in list. One thing not to do is remove items from a list while a for loop is going through it: the loop skips the item after each one removed, with no error. Loops - For and While shows why, and the fix of building a new list instead.

sort() changes the list; sorted() makes a new one

Python has two ways to sort: one changes the list, like the methods above, and one makes a new list, like +:

nums = [3, 1, 2]
ordered = sorted(nums)
print(ordered, nums)

nums.sort()
print(nums)

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

# ✅ Expected output:
# [1, 2, 3] [3, 1, 2]
# [1, 2, 3]
# [3, 2, 1]

sorted() is a built-in function: it returns a new, sorted list and leaves the original alone. .sort() is a method that sorts the list itself. Both take reverse=True for largest first. Like the other methods that change a list in place, .sort() returns None, so assigning its result back throws the list away:

nums = [3, 1, 2]
nums = nums.sort()
print(nums)
print(nums[0])

# ✅ Expected output:
# None

# ✅ Expected error:
# TypeError: 'NoneType' object is not subscriptable

"Not subscriptable" means the value can't be indexed with square brackets. When you see it, look for a line like nums = nums.sort() or nums = nums.append(4): the method changed the list and handed back None. pop() is the exception, since it changes the list and returns the item. Reversing works the same two ways:

nums = [1, 2, 3]
backwards = nums[::-1]
print(backwards, nums)

nums.reverse()
print(nums)

# ✅ Expected output:
# [3, 2, 1] [1, 2, 3]
# [3, 2, 1]

.reverse() flips the list in place. nums[::-1] is a slice, which makes a new list, here a reversed one; Slicing Lists & Strings covers the [start:stop:step] notation.

Text sorts by character code, so capitals come before lower case, as "Zebra" < "apple" showed in Operators and Expressions. A list that mixes numbers and text can't be sorted: sorted([3, "1", 2]) stops with TypeError: '<' not supported between instances of 'str' and 'int'. To sort by length, by one part of each item or ignoring case, you give sorted() a key, which Sorting with sorted() & key covers.

Totals: sum, min and max

Three more built-in functions work on a whole list of numbers at once, and with len() they make an average:

temps = [12, 19, 7, 15]
print(sum(temps), min(temps), max(temps))
print(sum(temps) / len(temps))

# ✅ Expected output:
# 53 7 19
# 13.25

min() and max() work on text too, in the order sorted() uses. An empty list is where all of these need care. sum() of an empty list is 0, but the average then divides by len(), which is 0 too:

temps = []
print(sum(temps))
print(sum(temps) / len(temps))

# ✅ Expected output:
# 0

# ✅ Expected error:
# ZeroDivisionError: division by zero

max() and min() of an empty list stop with a ValueError, whose wording differs between Python versions. An empty list counts as false in an if, as in Control Flow, so if temps: before the calculation, or a guard clause in a function, keeps it safe.

Two names, one list

b = a copies nothing: it gives the same list a second name, as Variables and Data Types showed for numbers. The difference is that a list can be changed in place, so a change made through either name shows through both:

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

# ✅ Expected output:
# [1, 2, 3, 4]
# True

is asks whether two names refer to the same value, and here they do. A function's parameter is one more name for the list you pass in, so a function can change the caller's list:

def add_bonus(scores):
    scores.append(100)

mine = [70, 80]
add_bonus(mine)
print(mine)

# ✅ Expected output:
# [70, 80, 100]

When you want a separate list, copy it:

a = [1, 2, 3]
b = a.copy()
c = list(a)
b.append(4)
print(a, b)
print(c == a, c is a)

# ✅ Expected output:
# [1, 2, 3] [1, 2, 3, 4]
# True False

.copy() and list() both make a new list holding the same items, so ==, which compares items, says True, and is says False. The copy is shallow, though: when the items are themselves lists, the new list holds those same inner lists:

grid = [[1, 2], [3, 4]]
copied = grid.copy()
copied[0].append(99)
print(grid)

# ✅ Expected output:
# [[1, 2, 99], [3, 4]]

copy.deepcopy(), from Python's copy module, copies the inner lists too. import copy loads the module, as import math did in Operators and Expressions:

import copy

grid = [[1, 2], [3, 4]]
copied = copy.deepcopy(grid)
copied[0].append(99)
print(grid)
print(copied)

# ✅ Expected output:
# [[1, 2], [3, 4]]
# [[1, 2, 99], [3, 4]]

Lists inside lists

An item can be a list, which is how a table or a grid is usually held:

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

for row in grid:
    print(sum(row))

# ✅ Expected output:
# [4, 5, 6]
# 6
# 2 3
# 6
# 15

grid[1] is the second row, itself a list, so a second index picks an item from it: grid[1][2] is item 2 of row 1, both counted from 0. len(grid) counts the rows. One way of building a grid catches people out. * repeats a list as it repeats text, so [0] * 3 is a list of three zeros, but repeating a list of lists repeats the same inner list:

board = [[0] * 3] * 2
board[0][0] = 5
print(board)

# ✅ Expected output:
# [[5, 0, 0], [5, 0, 0]]

Both rows are one list with two names, as in the previous section. Build each row on its own, in a loop; Comprehensions shows a one-line way to do the same:

board = []
for i in range(2):
    board.append([0] * 3)
board[0][0] = 5
print(board)

# ✅ Expected output:
# [[5, 0, 0], [0, 0, 0]]

The other collections

A list is Python's general-purpose collection, and each of the others has a lesson of its own. Dictionaries look values up by a key instead of a position. Tuples are sequences that can't be changed, like the pair a function returns. Sets hold each value once and answer in quickly.

For loops over lists, enumerate & zip gives each item's position alongside it and goes through two lists in step. And String Methods has split(), which turns text into a list, and join(), which turns a list of strings back into text.

Practice: a scoreboard

Fill the three blanks with the values in the hint lines, in order: add a fourth score, make a copy sorted highest first, and print the best score from it. The second print shows that the original list kept its order.

scores = [72, 91, 58]
scores.___(84)
ranked = ___(scores, reverse=True)

print(ranked)
print(scores)
print("Best:", ranked[___])

# 👉 replace ___ with append
# 👉 replace ___ with sorted
# 👉 replace ___ with 0

# ✅ Expected output:
# [91, 84, 72, 58]
# [72, 91, 58, 84]
# Best: 91

On your own: a faulty sensor

Six temperature readings came in, readings = [12, 19, 7, 15, 22, 9], and the lowest one is from a faulty sensor. Remove it, then print how many readings are left and their average rounded to one decimal place with round(). Finally, build a new list of the readings above that average and print it. You should get 5 readings, an average of 15.4, and two readings above it. Then compare with this solution:

readings = [12, 19, 7, 15, 22, 9]
readings.remove(min(readings))

average = sum(readings) / len(readings)
above = []
for r in readings:
    if r > average:
        above.append(r)

print(len(readings), round(average, 1))
print(above)

# ✅ Expected output:
# 5 15.4
# [19, 22]

min(readings) finds the value and remove() deletes it, since remove() works by value. The new list starts empty and the loop appends to it, which leaves readings as it was.

Practice quiz

nums = [10, 20, 30]. What does print(nums[3]) do?

  • Prints 30
  • Prints None
  • Stops with IndexError: list index out of range
  • Prints 10

Answer: Stops with IndexError: list index out of range. Three items have indexes 0, 1 and 2, so 3 is one past the end.

a = [1, 2], then b = a and b.append(3). What is a now?

  • [1, 2]
  • [1, 2, 3]
  • [3]
  • An error

Answer: [1, 2, 3]. b = a gives the same list a second name, so the change shows through both.

nums = [3, 1, 2], then nums = nums.sort(). What is nums now?

  • [1, 2, 3]
  • [3, 1, 2]
  • None
  • An error

Answer: None. .sort() sorts the list in place and returns None, which the assignment then stores.

x = [1, 2], then x.append([3, 4]). What is len(x)?

  • 3
  • 4
  • 2
  • An error

Answer: 3. append() adds its argument as one item, so x is [1, 2, [3, 4]].

letters = ['a', 'b', 'c']. What does letters.pop() return?

  • None
  • 'a'
  • The list ['a', 'b']
  • 'c'

Answer: 'c'. pop() with no argument removes the last item and returns it.

Which line removes the value 'b' from letters = ['a', 'b', 'c']?

  • letters.remove('b')
  • letters.pop('b')
  • del letters['b']
  • letters.delete('b')

Answer: letters.remove('b'). remove() deletes by value. pop() and del take a position, and lists have no delete() method.

grid = [[1, 2], [3, 4]]. What is grid[1][0]?

  • 2
  • 3
  • [3, 4]
  • 1

Answer: 3. grid[1] is the second row, [3, 4], and its item 0 is 3.

nums = [5, 2, 8], then result = sorted(nums). What is nums afterwards?

  • [2, 5, 8]
  • None
  • [8, 5, 2]
  • [5, 2, 8]

Answer: [5, 2, 8]. sorted() returns a new list and leaves the original alone.

Continue this course

Frequently asked questions

Is a Python list the same as an array?

A list does the job an array does in most other languages, with two differences: it grows and shrinks as you add and remove items, and it can hold values of different types. For large amounts of numbers, NumPy's arrays are faster and use less memory; the NumPy course covers them.

How do I remove duplicates from a list?

The quick way is list(set(values)): a set keeps one of each value, but not their order. To keep the order, list(dict.fromkeys(values)) keeps the first of each value where it was. The Sets lesson explains how sets work.

Related lessons