This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: More on lists

List operators

face Josiah Wang Joe Stacey

Like strings, the operators + and * have been overloaded for lists.

So, you can concatenate two lists by ‘adding’ the list together, and replicate elements in a list by ‘multiplying’ it with a scalar.

>>> print([1, 2] + [3, 4, 5])
[1, 2, 3, 4, 5]
>>> print([1, 2] * 3)
[1, 2, 1, 2, 1, 2]

Looking forward to yet another quiz? 😊

1 2 3 4 5

Question 1

What is the output of the following code snippet? Type Error if it results in an error.

first_list = [1, 2]
second_list = ["a", "b"]
combined_list = first_list + second_list
print(combined_list)

[1, 2, "a", "b"]
Explanation:

The elements inside a list does not have to be of the same type. So you can add a list of int to a list of str. Of course, think carefully whether this is the best way to use a list, as your code might be a bit unreadable this way.

Question 2

What is the output of the following code snippet? Type Error if it results in an error.

letters = ["a", "b"]
letters = letters + "c"
print(letters)

Error
Explanation:

Python tells you the error exactly: TypeError: can only concatenate list (not "str") to list. While you can concatenate lists of different types, you cannot concatenate lists with anything else with the plus operator. If you intend to append "c" to ["a", "b"], then you can convert the "c" into a list, e.g. letters + ["c"] or letters + list("c").

Question 3

What is the output of the following code snippet? Type Error if it results in an error.

numbers = [4, 5]
print(3 * numbers)

[4, 5, 4, 5, 4, 5]

Question 4

What is the output of the following code snippet? Type Error if it results in an error.

numbers = [4, 5]
print(numbers * numbers)

Error
Explanation:

Like strings, you need to 'multiply' the list with a scalar. Try this out in an interactive prompt to see the error message. It should look familiar!

Question 5

What is the output of the following code snippet? Type Error if it results in an error.

numbers = [1, 2]
replicated_numbers = [numbers] * 3
print(replicated_numbers)

[[1, 2], [1, 2], [1, 2]]
Explanation:

Note that in Line 2, [numbers] will result in a nested list [[1,2]]. The multiplication operator will replicate the element [1,2] inside the list, resulting in a nested list with 3 elements. So [number] * 3 is different from number * 3!