Informatics Practices · Ch 4 — Working with Lists and Dictionaries
Concatenation
Concatenation
Concatenation is the merging of two or more values into one — the way two strings can be joined end to end. Python allows us to join two or more lists the same way, using the concatenation operator, written with the symbol +. The result is a single list containing the elements of the first list followed by the elements of the second.
>>> list1 = [1,3,5,7,9] # first five odd integers
>>> list2 = [2,4,6,8,10] # first five even integers
>>> list1 + list2 # elements of list1 followed by list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
It works just as well on lists of strings:
>>> list3 = ['Red','Green','Blue']
>>> list4 = ['Cyan', 'Magenta', 'Yellow', 'Black']
>>> list3 + list4
['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
The originals are not changed
Concatenation builds a new list; it does not touch the operands. After the operations above, list1, list2, list3 and list4 all remain exactly as they were. The joined list that appears on the screen is a fresh value — and if nothing is done with it, it is simply displayed and lost.
So, if we want to use the result of concatenating two lists, we must capture it with an assignment operator:
>>> newList = list1 + list2
>>> newList
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
Now the combined list has a name and can be used later, while list1 and list2 still hold their original five elements each.
Both operands must be lists
The concatenation operator + requires that both operands be of list type. Trying to concatenate a list with a value of some other data type raises a TypeError:
>>> list1 = [1,2,3]
>>> str1 = "abc"
>>> list1 + str1
TypeError: can only concatenate list (not "str") to list
Even though a string is itself a sequence, Python refuses to mix the two types under +. A list joins only with another list. …