Legends ofPythos
Claim your name
Python Basics

Lists

Lesson 8 of 13

Watch the lesson0:58 ยท with Sigrid
You know how to store one value in a variable, like age = 25. But what if you need to track three grades or five friends? You do not want ten separate variables. A list solves this by holding multiple items inside one ordered collection.
You create a list using square brackets []. Inside, you place your values separated by commas. The order matters because Python remembers the position of each item.
fruits = ['apple', 'banana', 'cherry']
print(fruits)
# Output: ['apple', 'banana', 'cherry']
Creating and printing a list
The variable fruits now holds three strings. When you print it, Python shows the entire collection in one line with brackets.

Indexing

To get a specific item out of a list, you use indexing. Python counts positions starting at 0, not 1. The first item is index 0, the second is 1.
colors = ['red', 'green', 'blue']
print(colors[0])   # red
print(colors[2])   # blue
print(colors[-1])  # also blue (last item)
Accessing items by index
colors[0] grabs the first string. colors[-1] is a handy shortcut for the last item, which helps when you do not know how long the list is.

Length and Membership

You often need to know how many items are in a list. Use len() for this count. You can also check if a value exists inside the list using the keyword in.
nums = [10, 20, 30]
print(len(nums))       # 3
print(20 in nums)      # True
print(99 in nums)      # False
Checking length and membership
len() returns an integer count. The in check returns a boolean: True if found, or False otherwise.

Modifying Lists

Lists are mutable, meaning you can change them after creation. The .append() method adds a new item to the very end of the list.
todo = ['eat', 'sleep']
todo.append('code')   # adds to end
print(todo)           # ['eat', 'sleep', 'code']
Adding an item
You can also remove items. .remove(item) deletes the first occurrence of a specific value. .pop() removes the last item and hands it back to you; give it a position, like .pop(0), to take that item instead.
todo.remove('eat')      # removes 'eat'
last_item = todo.pop()  # removes last item
print(last_item)        # code
Removing items

Your turn

0 of 3 solved

Exercise 1

+30 XP
Create a list called scores containing the numbers 85, 92, and 78. Print the length of this list.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+30 XP
Start with a list animals containing 'cat', 'dog', and 'bird'. Add the string 'fish' to the end of the list. Then print the last item in the list.
Write your Python here.

Run your code to check it against the tests.

Exercise 3

+30 XP
Create a list numbers with values [5, 10, 15, 20]. Create an empty list called sub_list. Use indexing to get the items at index 1 and index 2 (which are 10 and 15) and append them to sub_list. Print this new sub-list.
Write your Python here.

Run your code to check it against the tests.