Creating Lists

You create a list by writing its elements between square brackets [ ], separated by commas:

shopping = ["apples", "chocolate", "bread rolls"]

Elements can be any values: text, numbers or booleans (True and False). You can even mix them in one list. A list can also be empty, with no elements at all: []. You'll learn how to add elements to it later in this lesson.

prices = [45, 12.5, 30]
mixed = ["text", 123, True]
nothing_yet = []
print(prices)
print(mixed)
print(nothing_yet)

This prints:

[45, 12.5, 30]
['text', 123, True]
[]

Numbers and booleans are printed without quotes, just as you write them in code. In practice, though, a list usually holds values of one kind, such as a list of names or a list of prices.

Watch out for the commas. Without a comma between two numbers, the program doesn't run at all: [45 12.5] ends with SyntaxError: invalid syntax. Perhaps you forgot a comma? Without a comma between two texts, it's worse: there is no error, Python just joins the two texts into one. ["apples" "chocolate"] is a list with a single element, 'appleschocolate'.

You'll often want to print a list with a label. In print(), separate the label and the list with a comma, or put the list in an f-string. Both print the list with its brackets and quotes:

shopping = ["apples", "chocolate", "bread rolls"]
print("To buy:", shopping)
print(f"To buy: {shopping}")

This prints:

To buy: ['apples', 'chocolate', 'bread rolls']
To buy: ['apples', 'chocolate', 'bread rolls']

Joining with + doesn't work: "To buy: " + shopping ends with TypeError: can only concatenate str (not "list") to str. Text can only be joined with text, not with a list. You've seen the same error when joining text with a number.

Instructions

Create a list with the elements "Peter", "Tim" and "Lucy", in this order, and store it in a variable named colleagues.

Print the list with the label Colleagues:, so that the output is Colleagues: ['Peter', 'Tim', 'Lucy'].

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/12