Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
9.7. Concatenation and Repetition¶
As with strings, the
+ operator concatenates lists and tuples.
It is important to see that these operators create new lists/tuples from the elements of the operand lists/tuples. 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).
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
newlist = fruit + numlist, it refers to a completely new list formed by making copies of the items from
numlist. You can see this very clearly in the CodeLens object diagram. The objects are different.
WP: Adding types together
Beware when adding different types together! Python doesn’t understand how to concatenate different
types together. Thus, if we try to add a string to a list with
['first'] + "second" then the
interpreter will return an error. To do this you’ll need to make the two objects the same type. In this
case, it means putting the string into its own list and then adding the two together like so:
['first'] + ["second"]. This process will look different for other types though. Remember that there
are functions to convert types!
The following code won’t run, because the third line attempts to add two different types (a list and a tuple). Run it to see the error.
Fix the error above by converting veggies1 to a list in the expression on line 3:
* operator repeats the items in a list or tuple a given number of times. So, repetition of a list of 2 items 4 times will give a list
with 8 items.
As with concatenation, these operations do not have any effect on the input lists/tuples, they create new lists. You can reassign the new list back to the same variable name though:
Check your understanding