BeginnerLesson firstCategory 18 of 20

Lists — Basics

Create and access list elements. Read the lesson first, then move through the exercises in order.

6 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Create and Print Lists

Study Material

Read the full lesson

Storing many things together

So far, every variable we have created holds a single piece of data: one string, one integer, one boolean.

But what if you are writing a to-do list app? You can't create task1, task2, task3, ... up to task100. That would be a nightmare.

You need a single container that can hold multiple items. In Python, the most common container is the List.

Creating a List

Lists are created using square brackets [], with commas separating the items.

python
# A list of strings fruits = ["apple", "banana", "cherry"] # A list of numbers scores = [95, 82, 100, 75] # A mixed list (Python doesn't mind!) mixed_box = ["hello", 42, True, 3.14] # An empty list empty_list = []

Accessing items in a list

Does string indexing and slicing look familiar? Lists use the exact same system!

Lists are zero-indexed.

python
fruits = ["apple", "banana", "cherry", "date"] # Get the first item print(fruits[0]) # Output: apple # Get the third item print(fruits[2]) # Output: cherry # Get the last item using negative indexing print(fruits[-1]) # Output: date

You can even slice out chunks of a list just like you did with strings:

python
# Get a new list with items from index 1 up to (but not including) index 3 print(fruits[1:3]) # Output: ['banana', 'cherry']

Finding the length

Just like strings, you can use the built-in len() function to find out how many items are inside a list.

python
colors = ["red", "green", "blue"] amount = len(colors) print(f"There are {amount} colors.") # Output: There are 3 colors.

Lists and for loops are best friends

Lists are meant to be iterated over. for loops make this incredibly elegant.

python
guests = ["Alice", "Bob", "Charlie"] for guest in guests: print(f"Welcome to the party, {guest}!")

What this lesson should give you

After this lesson, you should understand how to:

  • create a list using square brackets []
  • access individual list items using zero-based indexing like my_list[0]
  • grab the last item using my_list[-1]
  • find the number of items in a list using the len() function
  • elegantly iterate through every item in a list using a for loop

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.