Lists: Many Items, Plus Indexing and Append

 

What you’ll learn in this lesson

  • What a list is, and why one variable sometimes needs to hold many values
  • How to make a list and read items by position
  • How to count a list’s items
  • How to add an item with append and change an item by position
  • How to loop through a whole list

One variable, many values

So far every variable has held one value: one name, one number, one
string. But real programs deal in groups — a class of students, a
week of temperatures, a shopping list. A list stores many values
in a single variable, in order, inside square brackets, separated by
commas:

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

Output:

['apple', 'banana', 'cherry']

Python prints the whole list back, brackets and all, so you can see
exactly what is inside. The items can be any mix of kinds — strings,
numbers, booleans — though in practice a list usually holds one kind
of thing, because that keeps the code readable.


Reading items by position

Like string characters in Lesson 6, list items are counted from 0.
The first item is position 0, the second is position 1, and so on:

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

Output:

apple
banana
cherry

Asking for a position past the end gives an error, just as with
strings — there is no fourth fruit in a three-item list. A handy
shortcut: position -1 means the last item, -2 the second-to-last,
and so on:

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

Output:

cherry

len() counts a list’s items, exactly as it counts a string’s
characters:

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

Output:

3

Changing a list: append and replace

Lists are changeable — unlike strings, you can alter them after
making them. The two changes beginners use most are adding to the end
and replacing one item:

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)
fruits[1] = "blueberry"
print(fruits)

Output:

['apple', 'banana', 'cherry', 'orange']
['apple', 'blueberry', 'cherry', 'orange']

append() sticks a new item on the end. fruits[1] = "blueberry"
replaces whatever was at position 1 — the same bracket notation you
use to read an item, now on the left of the = sign, which means
“store” (Lesson 4). Read the second output carefully: the order of
the other items did not change; only position 1 did.


Looping through a list

Lists and loops (Lesson 9) belong together. A for loop walks a list
one item at a time, so you can do something with every item without
knowing in advance how many there are:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print("I like " + fruit)

Output:

I like apple
I like banana
I like cherry

The loop variable fruit takes each value in turn: first "apple",
then "banana", then "cherry". If you later append "orange" to
the list, the same loop prints four lines with no other change. That
is the real power of lists: code that works for three items works for
three hundred, because the loop adapts to the list.


Lists: Many Items, Plus Indexing and Append

Python for Absolute Beginners · Lesson 12

What you’ll learn

  • What a list is, and why one variable sometimes needs to hold many values
  • How to make a list and read items by position
  • How to count a list's items
  • How to add an item with append and change an item by position
  • How to loop through a whole list
1 / 15

One variable, many values

  • So far every variable has held one value: one name, one number, one string
  • But real programs deal in groups — a class of students, a shopping list
  • A list stores many values in a single variable, in order
  • Items sit inside square brackets, separated by commas
  • Items can mix kinds, but usually hold one kind of thing, to keep code readable
2 / 15

Make a list

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

['apple', 'banana', 'cherry']

Python prints the whole list back, brackets and all, so you can see exactly what is inside.

3 / 15

Reading items by position

  • Like string characters, list items are counted from 0
  • The first item is position 0, the second is position 1, and so on
  • Asking for a position past the end gives an error — there is no fourth fruit in a three-item list
  • A handy shortcut: position -1 means the last item, -2 the second-to-last
4 / 15

Read by position

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

apple
banana
cherry

The same bracket notation you use to make the list, now with a position inside.

5 / 15

The last item shortcut

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

cherry

Minus 1 is a handy shortcut for the last item.

6 / 15

Counting with len

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

3

len() counts a list's items, exactly as it counts a string's characters.

7 / 15

Changing a list: append and replace

  • Lists are changeable — unlike strings, you can alter them after making them
  • append() sticks a new item on the end
  • list[1] = … replaces whatever was at position 1
  • The bracket notation on the left of = means “store”
  • The order of the other items does not change — only position 1 does
8 / 15

Append and replace

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)
fruits[1] = "blueberry"
print(fruits)

['apple', 'banana', 'cherry', 'orange']
['apple', 'blueberry', 'cherry', 'orange']

Read the second output carefully: only position 1 changed.

9 / 15

Looping through a list

  • Lists and loops belong together: a for loop walks a list one item at a time
  • The loop variable takes each value in turn
  • You do not need to know in advance how many items there are
  • Append an item later, and the same loop prints one more line with no other change
  • Code that works for three items works for three hundred
10 / 15

Loop through a list

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print("I like " + fruit)

I like apple
I like banana
I like cherry

The loop adapts to the list, however many items it holds.

11 / 15

Hands-on exercise

  • Make a list of four of your favorite foods; print the whole list, then just the first item
  • Print how many items your list has with len()
  • Append a fifth food, print the list again, and confirm it grew
  • Replace the second item with something else and print the list
  • Write a loop that prints “I like …” for every item in your list
12 / 15

Key takeaways

  • A list stores many values in order, in one variable, in square brackets.
  • Positions start at 0; -1 is the last item; len() counts items.
  • Lists are changeable: append() adds to the end, list[i] = … replaces one item.
  • A for loop over a list handles every item, however many there are.
13 / 15

Take the quiz

Take the Lesson 12 quiz — 5 quick questions to check what you learned.

14 / 15

Next lesson

Dictionaries: Labeled Storage

15 / 15

Press play on any slide and the lesson plays on by itself from there. You can still click Next or click a slide to move on.

Download the Lesson 12 slides (PowerPoint, with narration)

Download the Lesson 12 slides (PDF)

Hands-on exercise

  1. Make a list of four of your favorite foods and print the whole
    list, then print just the first item.
  2. Print how many items your list has with len().
  3. Append a fifth food, print the list again, and confirm it grew.
  4. Replace the second item with something else and print the list.
  5. Write a loop that prints "I like ..." for every item in your list.

Lesson 12: Lists: Many Items, Plus Indexing and Append

A list holds many items in order. append adds one item at the end and len counts the items. Change the fruit you add and run again.

Loading Python… this can take a few seconds the first time. Please wait — the Run button will become available when Python is ready.

Try this: Change the fruit to mango and press Run again — mango appears at the end of the list.

The code that runs



Output

Press Run to see the output here.

Practice file

Save this as lesson12-practice.py and run it with F5 in IDLE.

# Lesson 12: Lists — Many Items, Indexing, Append
# WHAT TO DO: A list stores many values in order, inside square
# brackets. Positions start at 0. This list of favorite foods has one
# placeholder item. Fill in line 11: replace TODO with a real food
# of your own, keeping it inside quotes.
# HINT: Only change the word TODO. The rest of the program already
# prints the list, its first item, how many items it has, adds a fifth
# food with append(), and prints "I like ..." for every item.
# Run with F5 in IDLE. You are done when no TODO appears in the output.

foods = ["pizza", "TODO", "pasta", "salad"]  # <-- CHANGE THIS LINE
print(foods)
print(foods[0])
print(len(foods))
foods.append("soup")
print(foods)
for food in foods:
    print("I like " + food)

Key takeaways

  • A list stores many values in order, in one variable, in square brackets.
  • Positions start at 0; -1 is the last item; len() counts items.
  • Lists are changeable: append() adds to the end, list[i] = ... replaces one item.
  • A for loop over a list handles every item, however many there are.

Next lesson: Dictionaries.


Quick quiz

  1. What is a list, and what brackets does it use?
  2. In ["apple", "banana", "cherry"], what is at position 0, and what is at position -1?
  3. What does len() do to a list?
  4. What is the difference between fruits.append("orange") and fruits[1] = "blueberry"?
  5. Why does a loop over a list still work if the list later grows?

Answer key: 1. Many values stored in order in a single variable, inside square brackets. 2. Position 0 is "apple"; position -1 is "cherry", the last item. 3. It counts how many items the list has. 4. append() adds a new item at the end; fruits[1] = ... replaces the item already at position 1. 5. Because the loop walks whatever items are in the list at run time, however many there are.