6. Concatenation and Repetition¶
Also, as with strings, the +
operator concatenates lists. Similarly, the *
operator repeats the items in a list a given number of times.
It is important to see that these operators create new lists from the elements of the operand lists. If you concatenate a list with 2 items and a list with 4 items, you will get a new list with 6 items (not a list with two sublists). Similarly, repetition of a list of 2 items 4 times will give a list with 8 items.
One way for us to make this more clear is to run a part of this example in codelens. As you step through the code, you will see the variables being created and the lists that they refer to. Pay particular attention to the fact that when new_list
is created by the statement new_list = fruit + num_list
, it refers to a completely new list formed by making copies of the items from fruit
and num_list
. You can see this very clearly in the codelens object diagram. The objects are different.
Note that concatenation is similar to the append method, but with the important difference that append
only modifies the original list. It does not create a new list as concatenation does.
Also be aware that you can only concatenate lists together. So if you wanted to concatenate the fruit
list above with a string like "kiwi"
, you would need to put it in square brackets:
more_fruit = fruit + ["kiwi"]
Check your understanding
- 6
- Concatenation does not add the lengths of the lists.
- [1, 2, 3, 4, 5, 6]
- Concatenation does not reorder the items.
- [1, 3, 5, 2, 4, 6]
- Yes, a new list with all the items of the first list followed by all those from the second.
- [3, 7, 11]
- Concatenation does not add the individual items.
What is printed by the following statements?
alist = [1, 3, 5]
blist = [2, 4, 6]
print(alist + blist)
- 9
- Repetition does not multiply the lengths of the lists. It repeats the items.
- [1, 1, 1, 3, 3, 3, 5, 5, 5]
- Repetition does not repeat each item individually.
- [1, 3, 5, 1, 3, 5, 1, 3, 5]
- Yes, the items of the list are repeated 3 times, one after another.
- [3, 9, 15]
- Repetition does not multiply the individual items.
What is printed by the following statements?
alist = [1, 3, 5]
print(alist * 3)
- [4, 2, 8, 6, 5, 999]
- You cannot concatenate a list with an integer.
- Error, you cannot concatenate a list with an integer.
- Yes, in order to perform concatenation you would need to write alist+[999]. You must have two lists.
What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
alist = alist + 999
print(alist)