livepython.net
CHAPTER 09Python Lists
9.1  LISTS

Python Lists: Create, Print and Count Items

What Is a List in Python?

A list stores many values in one variable. You write the values inside square brackets [ ], with a comma between them.

Think of it like a shopping list on paper: one sheet, many items, in the order you wrote them down.

PYTHONedit me
fruits = ["apple", "banana", "mango"]
print(fruits)
OUTPUT
['apple', 'banana', 'mango']

The rules

  • A square bracket [ starts the list, and ] ends it.
  • A comma , goes between two values.
  • Each value in a list is called an item (some books say element).
  • A list keeps the order you wrote. Python never shuffles it by itself.

Python prints a list the way you would type it, brackets and commas included. Notice that the strings now show single quotes '. That's only how Python shows text inside a list. Single and double quotes mean the same thing (chapter 5).

Why not many variables?

Without a list, three friends need three variables:

PYTHONedit me
friend1 = "Sunny"
friend2 = "Rocky"
friend3 = "Lucky"
print(friend1, friend2, friend3)
OUTPUT
Sunny Rocky Lucky

With a list, one name holds them all:

PYTHONedit me
friends = ["Sunny", "Rocky", "Lucky"]
print(friends)
OUTPUT
['Sunny', 'Rocky', 'Lucky']

A fourth friend? Add one more item, not one more variable. And in chapter 10, a for loop will visit every item of a list for you.

Common beginner doubt: a missing comma

PYTHONedit me
colors = ["red" "blue"]
print(colors)
OUTPUT
['redblue']

No error, but only one item! Two strings written side by side are glued into one string. Python saw "redblue". Always check the commas between your items.

A list holds many values, in order, inside square brackets.

your turnPredict the output

What will this print?

nums = [3, 1, 2] print(nums)
Your turn! What will this code show on the screen?
your turnPick the right idea

Which line makes a list of three names?

Think about it, then pick one.

Count the Items: len() and the Empty List

In chapter 5, len() counted the characters of a string. Give it a list, and len() counts the items instead.

Think of counting the eggs in a tray: you count the eggs, not how big each egg is.

PYTHONedit me
friends = ["Sunny", "Rocky", "Lucky"]
print(len(friends))
OUTPUT
3

The rules

  • len() of a list counts items, not letters. "Sunny" is one item, even with five letters.
  • A list with no items is an empty list: []. Its length is 0.
  • len() gives a whole number, so you can calculate with it.

The empty list

An empty list is a great starting point. You make the list first and add items later (you'll see how in topic 4).

PYTHONedit me
cart = []
print(cart)
print(len(cart))
OUTPUT
[]
0

len() in a sentence

The result of len() is a number like any other. Put it in an f-string from chapter 5:

PYTHONedit me
tasks = ["wash the car", "buy milk", "call Rocky", "learn Python"]
print(f"You have {len(tasks)} tasks today.")
OUTPUT
You have 4 tasks today.

Common beginner doubt: items or letters?

Is len(["wash the car"]) 1 or 12? It's 1. The list has one item. Only len("wash the car"), without the brackets, counts the 12 characters of the string.

PYTHONedit me
print(len(["wash the car"]))
print(len("wash the car"))
OUTPUT
1
12

len() counts the items in a list. An empty list, [], has 0 items.

your turnType the output

Type what this prints

pets = ["cat", "dog", "parrot"] print(len(pets))
Read the code line by line, then type the output exactly.
your turnFill the gap

Make an empty list

cart = ? print(len(cart))

It should print: 0

Which piece makes this code work?

Lists Can Hold Any Type

A list can hold any type of value from chapter 5: strings, whole numbers, decimals, booleans, and even a mix of them.

Think of a school bag: a book, a bottle and your keys are very different things, but they all fit in one bag.

PYTHONedit me
marks = [85, 92, 78]
prices = [9.99, 4.5, 20.0]
answers = [True, False, True]
print(marks)
print(prices)
print(answers)
OUTPUT
[85, 92, 78]
[9.99, 4.5, 20.0]
[True, False, True]

A list can also mix types. Here are some facts about Sunny: a name, an age, a height and whether he's a student:

PYTHONedit me
sunny = ["Sunny", 25, 1.75, True]
print(sunny)
print(len(sunny))
OUTPUT
['Sunny', 25, 1.75, True]
4

The rules

  • Strings show quotes in the printout. Numbers and booleans don't.
  • So 25 is a number and '25' is text. The quotes tell you which one you have.
  • The type of a list itself is list. Check it with type() from chapter 4:
PYTHONedit me
scores = [10, 20]
print(type(scores))
OUTPUT
<class 'list'>

Good and Avoid

Good: one kind of thing per list. All marks in one list, all names in another. Easy to read, and you can add up the numbers later (topic 5).

Avoid: numbers in quotes. They look like numbers, but they're text:

PYTHONedit me
marks = [85, "92"]
print(marks)
OUTPUT
[85, '92']

The printout gives it away: '92' has quotes, so it's a string. You can't do maths with it.

Common beginner doubt: when is a mixed list okay?

A short mixed list, like Sunny's facts above, works. But you have to remember that position 2 is the height and position 3 is the student flag. For records like that, Python has a better tool, the dictionary. You'll learn it in chapter 13.

A list can hold any type, even a mix. Quotes in the printout mean text.

your turnPredict the output

What will this print?

data = ["Rocky", 30, "30"] print(data)
Your turn! What will this code show on the screen?

Join and Repeat Lists with + and *

Lists work with + and *, just like strings in chapter 5. + joins two lists into one new list, and * repeats a list.

Think of two short trains: hook them together, and you get one long train with the carriages in the same order.

PYTHONedit me
morning = ["tea", "toast"]
evening = ["rice", "dal"]
meals = morning + evening
print(meals)
print(len(meals))
OUTPUT
['tea', 'toast', 'rice', 'dal']
4
PYTHONedit me
row = [0] * 5
print(row)
OUTPUT
[0, 0, 0, 0, 0]

The rules

You writeYou get
[1, 2] + [3, 4][1, 2, 3, 4]
["Hi"] * 3['Hi', 'Hi', 'Hi']
[1, 2] + 3a TypeError
  • Both sides of + must be lists.
  • + makes a new list. morning and evening above are not changed.

Avoid: adding a single value with +

PYTHONedit me
nums = [1, 2]
nums = nums + 3
print(nums)
OUTPUT
TypeError: can only concatenate list (not "int") to list

Don't be scared of this error! It says: "I can join a list to a list, but 3 is an int". Concatenate is the fancy word for joining (chapter 5).

Good: put the value in brackets, so it becomes a list with one item:

PYTHONedit me
nums = [1, 2]
nums = nums + [3]
print(nums)
OUTPUT
[1, 2, 3]

This works, but there's a neater way to add one item: append(). You'll learn it in topic 4.

+ joins two lists into a new list, and * repeats a list. Both sides of + must be lists.

your turnFix the code

Fix the code so it prints: [1, 2, 3]

It should print: [1, 2, 3]

nums = [1, 2]
nums = nums + 3
print(nums)
This code does not work yet. Fix it, then press Run.
your turnType the output

Type what this prints

print(f"{7 // 2} and {7 % 2}")
Read the code line by line, then type the output exactly.

Practice: Lists

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 70.Python Program to Create and Print a ListEasySolve
  2. 71.Python Program to Build a Seat List with + and *MediumSolve