🎓 A1Learner
🔍

Python Lists

A list is an ordered collection, like a shopping list, that stores many values in one variable. A variable stores one value.

Your first list

Items sit inside square brackets. Commas separate the items.

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

Items can mix types

One list can hold text, numbers, and booleans together.

mixed = ["Ada", 36, True, 1.65]
print(mixed)

Count items with len()

The len() function works on lists, just like on strings.

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

Build a list with list()

The list() constructor builds a list from other values. Here it splits a word into its letters.

letters = list("cat")
print(letters)

The empty list

Two brackets with nothing inside make an empty list. You can fill it in later lessons.

todo = []
print(todo)
print(len(todo))

Example

temps = [21, 19, 23, 22, 20]
print(temps)
print("Days recorded:", len(temps))

Key points

  • List: an ordered collection of items, written inside square brackets [ ]
  • Ordered: the items stay in the order you put them in
  • Mutable: a list can change after you make it
  • You can replace, add, and remove items later.
  • Use len(my_list) to count how many items a list holds
  • Use list(...) to build a list from other values, such as the letters of a word
  • Python prints the stored form of each item.

In this example, temps holds five numbers, one for each day. The first print shows the whole list. The quotes are missing because the items are numbers, not text. The second print uses len(temps) to count the items. It prints the label Days recorded: and then the count 5.

Note

Printing a list shows text items in quotes, like 'apple'.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does print(len(["a", "b", "c", "d"])) print?