Python course menu
Python Lists: Create, Access, Change and Loop (Beginner Guide)
Everything a beginner needs to know about Python lists: creating lists, indexing and slicing, adding and removing items, sorting, looping, and the most common list mistakes.
On this page
A list stores many values in a single variable, in order. A shopping list, the scores in a game, the names of students in a class: whenever you have several of something, a list is usually the first tool to reach for.
Creating a list#
Write the items inside square brackets, separated by commas:
fruits = ["apple", "banana", "cherry"]
scores = [88, 92, 79, 95]
empty = []
print(fruits)
print(len(scores))['apple', 'banana', 'cherry']
4len() tells you how many items a list has. A list can hold any type of value, and even a mix, though in practice most lists hold one kind of thing.
Accessing items by index#
Each item has a position number called an index. Python counts from 0, so the first item is at index 0:
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[2])
print(fruits[-1]) # negative indexes count from the endapple
cherry
cherry-1 is a handy way to get the last item without knowing the list's length.
Slicing: get part of a list#
A slice returns a new list with a range of items. The syntax is list[start:stop], and the stop index is not included:
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4]) # items at index 1, 2, 3
print(numbers[:3]) # from the start up to index 3
print(numbers[3:]) # from index 3 to the end
print(numbers[::2]) # every second item
print(numbers[::-1]) # reversed copy[20, 30, 40]
[10, 20, 30]
[40, 50, 60]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]Changing items#
Lists are mutable, which means you can change them after creating them:
colors = ["red", "green", "blue"]
colors[1] = "yellow"
print(colors)['red', 'yellow', 'blue']Adding items#
tasks = ["email"]
tasks.append("meeting") # add to the end
tasks.insert(0, "coffee") # add at a position
tasks.extend(["report", "gym"]) # add several items
print(tasks)['coffee', 'email', 'meeting', 'report', 'gym']Removing items#
tasks = ["coffee", "email", "meeting", "report", "gym"]
tasks.remove("email") # remove the first matching value
last = tasks.pop() # remove and return the last item
first = tasks.pop(0) # remove and return the item at index 0
print(tasks)
print(last, first)['meeting', 'report']
gym coffeeUseful list operations#
scores = [88, 92, 79, 95, 92]
print(92 in scores) # is a value present?
print(scores.count(92)) # how many times?
print(scores.index(79)) # where is it first?
print(min(scores), max(scores), sum(scores))True
2
2
79 95 446Sorting#
sort() sorts the list in place (it changes the original). sorted() returns a new sorted list and leaves the original alone:
scores = [88, 92, 79, 95]
ranked = sorted(scores, reverse=True)
print(ranked)
print(scores)
scores.sort()
print(scores)[95, 92, 88, 79]
[88, 92, 79, 95]
[79, 88, 92, 95]Looping through a list#
The most common thing to do with a list is to go through it item by item with a for loop:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")I like apple
I like banana
I like cherryIf you also need the position, use enumerate():
for position, fruit in enumerate(fruits, start=1):
print(position, fruit)1 apple
2 banana
3 cherryLoops are explained fully in the Loops lesson.
Building a new list from an old one#
A common pattern is to start with an empty list and append to it inside a loop:
prices = [100, 250, 80]
with_tax = []
for price in prices:
with_tax.append(round(price * 1.18, 2))
print(with_tax)[118.0, 295.0, 94.4]round(..., 2) keeps two decimal places. Without it, 80 * 1.18 would print as 94.39999999999999 because of how decimals are stored in binary (see Data Types).
Python also has a shorter syntax for this called a list comprehension: with_tax = [round(price * 1.18, 2) for price in prices]. You will meet comprehensions properly later in the course.
Common mistakes#
Practice#
Practice exercise
You are given a list of exam scores:
scores = [72, 95, 58, 88, 64, 91]Write a program that:
- Prints the highest and lowest score.
- Prints the average score rounded to 1 decimal place.
- Creates a new list
passedcontaining only scores of 60 or more, and prints it.
Show hint
Use max(), min(), and sum(scores) / len(scores). For step 3, start with passed = [] and use a for loop with an if inside it.
Show solution
scores = [72, 95, 58, 88, 64, 91]
print("Highest:", max(scores))
print("Lowest:", min(scores))
average = sum(scores) / len(scores)
print("Average:", round(average, 1))
passed = []
for score in scores:
if score >= 60:
passed.append(score)
print("Passed:", passed)Highest: 95
Lowest: 58
Average: 78.0
Passed: [72, 95, 88, 64, 91]The six scores add up to 468, and 468 ÷ 6 = 78.0.
Key takeaway#
Finished this lesson?