10.5. Concatenation

Again, as with strings, the + operator concatenates lists.

 
1
fruit: [str]
2
fruit = ["apple", "orange", "banana", "cherry"]
3
print(str([1, 2] + [3, 4]))
4
print(str(fruit + ["kumquat"]))
5

(chp09_5)

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.

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 newlist is created by the statement new_list = fruit + to_add, it refers to a completely new list formed by making copies of the items from fruit and to_add. You can see this very clearly in the codelens object diagram. The objects are different.

Python 3.3
1fruit: [str]
2to_add: [str]
3new_list: [str]
4
5fruit = ["apple", "orange", "banana", "cherry"]
6to_add = ["kumquat"]
7new_list = fruit + to_add
Step 1 of 6
line that has just executed

next line to execute

Visualized using Online Python Tutor by Philip Guo
Frames
Objects

(chp09_concatid)

Check your understanding

list-6-1: What is printed by the following statements?

a_list: [int]
b_list: [int]
a_list = [1, 3, 5]
b_list = [2, 4, 6]
print(str(alist + blist))





You have attempted 1 of 4 activities on this page
Next Section - 10.6. Nested Lists