// python · beginner

Python Lists for Beginners: Store, Change and Loop Over Data

Learn how to create Python lists, add and remove items, loop over them, sort them and avoid the classic copying mistake. Includes a shopping-list project.

A variable holds one value. But what if you need to store the scores of a whole class, every item in a shopping basket, or all the words in a sentence? That’s what lists are for. They’re one of the most useful tools in Python, and you’ll use them in nearly every program you write.

Creating a list

A list is a collection of values inside square brackets, separated by commas:

python
scores = [72, 85, 90, 64]
languages = ["Python", "JavaScript", "SQL"]
empty = []
mixed = ["Ava", 15, True]   # allowed, but usually best avoided

Lists keep items in order, and they can contain duplicates.

Getting items out

Lists use the same indexing and slicing as strings, starting from 0:

python
languages = ["Python", "JavaScript", "SQL", "HTML"]

print(languages[0])      # Python
print(languages[-1])     # HTML
print(languages[1:3])    # ['JavaScript', 'SQL']
print(len(languages))    # 4

Changing items

Unlike strings, lists are mutable: you can change them in place.

python
scores = [72, 85, 90, 64]
scores[3] = 70
print(scores)   # [72, 85, 90, 70]

Adding items

python
basket = ["apples", "bread"]

basket.append("milk")          # add to the end
basket.insert(0, "coffee")     # add at position 0
basket.extend(["eggs", "jam"]) # add several at once

print(basket)
# ['coffee', 'apples', 'bread', 'milk', 'eggs', 'jam']

append adds one item. If you append a list, you get a list inside your list, which is why extend exists.

Removing items

python
basket = ["coffee", "apples", "bread", "milk"]

basket.remove("bread")     # remove by value (the first match)
last = basket.pop()        # remove and return the last item
first = basket.pop(0)      # remove and return the item at index 0

print(basket)   # ['apples']
print(last)     # milk
print(first)    # coffee

remove raises a ValueError if the item isn’t there, so check first when you’re not sure:

python
if "tea" in basket:
    basket.remove("tea")

Looping over a list

The for loop from the loops guide works beautifully with lists:

python
scores = [72, 85, 90, 64]
for score in scores:
    print(f"Score: {score}")

If you need the position as well as the value, use enumerate:

python
tasks = ["revise", "practise", "rest"]
for number, task in enumerate(tasks, start=1):
    print(f"{number}. {task}")
output
1. revise
2. practise
3. rest

Useful built-in functions

python
scores = [72, 85, 90, 64]

print(sum(scores))               # 311
print(max(scores))               # 90
print(min(scores))               # 64
print(sum(scores) / len(scores)) # 77.75 (the average)

Sorting

There are two ways to sort, and the difference matters:

python
scores = [72, 85, 90, 64]

ordered = sorted(scores)         # returns a NEW sorted list
print(ordered)   # [64, 72, 85, 90]
print(scores)    # [72, 85, 90, 64]  (unchanged)

scores.sort(reverse=True)        # sorts the list itself
print(scores)    # [90, 85, 72, 64]

A classic bug is writing scores = scores.sort(). The .sort() method changes the list and returns None, so you’d lose your list! Use either scores.sort() on its own or scores = sorted(scores).

Building a new list from an old one

Often you want a new list based on an existing one, such as every score with 5 bonus points added. The beginner-friendly way is a loop:

python
scores = [72, 85, 90, 64]
boosted = []
for s in scores:
    boosted.append(s + 5)
print(boosted)   # [77, 90, 95, 69]

Python also has a shorter form called a list comprehension, which does exactly the same thing in one line:

python
boosted = [s + 5 for s in scores]
passed = [s for s in scores if s >= 70]
print(passed)    # [72, 85, 90]

Use whichever you find easier to read. There’s no prize for squeezing code onto one line.

The copying trap

This surprises almost everyone:

python
a = [1, 2, 3]
b = a
b.append(4)
print(a)   # [1, 2, 3, 4]  (a changed too!)

b = a doesn’t copy the list. It gives the same list a second name. To make a real copy, use .copy():

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

Mini project: a shopping list

python
shopping = []

while True:
    item = input("Add an item (or press Enter to finish): ").strip()
    if item == "":
        break
    if item.lower() in [x.lower() for x in shopping]:
        print(f"{item} is already on the list.")
    else:
        shopping.append(item)

shopping.sort()
print(f"\nYou need {len(shopping)} items:")
for number, item in enumerate(shopping, start=1):
    print(f"{number}. {item}")

It ignores duplicates (even with different capital letters), sorts the list alphabetically and prints it numbered. Challenge: let the user type remove milk to take an item off the list.

Key points

  • Lists store many values in order: [a, b, c].
  • Indexing and slicing work just like strings, but lists can be changed.
  • append, insert and extend add items; remove and pop take them away.
  • sorted() returns a new list; .sort() changes the list and returns None.
  • b = a doesn’t copy a list; use a.copy().

Next, meet two more collections, the unchangeable tuple and the duplicate-free set, in Python Tuples and Sets.