Combining and Extending Lists
00:00
You can use Python operators to combine and repeat lists. The operators +
and +=
can be used to perform list concatenation, combining two lists together.
00:10 In this context, they can be called the concatenation and augmented concatenation operators. In both cases, the left and right-hand sides of the operator must be lists, otherwise you’ll get an error.
00:22
On the other hand, the *
and *=
operators are used for repetition, repeating a list some number of times, so you guessed it. You can call them the repetition and augmented repetition operators.
00:34
Also, to repeat a list, it must be multiplied by an integer. The key difference between the standard and augmented version of these operators is that the augmented version is more efficient in terms of memory and processing, a fact we’ll take a look at in the REPL. First, make a list of numbers and call it digits
, and why not make it the result of a concatenation itself.
00:56
digits = [0, 1] + [2, 3] +
[4, 5]
01:03
Look at digits
and you’ll see this chain of concatenation results in digits
storing a single list, [0, 1, 2, 3, 4, 5]
.
01:11
So to understand concatenation versus augmented concatenation, first check the identity of digits
using the id()
function: id(digits)
.
01:21 And the number you get will most likely be different from the number you see on my screen. But because IDs are unique, we’re really only checking to see whether it changes or stays the same.
01:30
So try concatenating digits
with another list.
01:34
digits = digits +
the list [6, 7]
.
01:38
Confirm digits
is now the combined list. Yep, [6, 7]
was added. And check the ID of digits
now. id(digits)
, and it’s changed, meaning that Python has actually created a new object to bind to the same variable name.
01:55
So what happens when you use augmented concatenation? Try this: digits += [8, 9]
.
02:04
And see what happened to digits
id.
02:08
Unchanged, meaning no extra objects had to be created. So how about the repetition operator? Using the *
operator, multiply digits
by the integer 2
.
02:19
And the result is, well, the integers 0
through 9
, twice. Pretty much what you’d expect. This operation is also commutative, meaning you can reverse the order of the operands and get the same result like 2 *
digits
also returns a list containing 0
to 9
twice.
02:38
And again, like concatenation, the augmented version, mutates the starting list. Confirm digits
identity again, id(digits)
, still the same.
02:48
That’s good. And use augmented repetition to multiply digits
by 3
this time and confirm that the ID has not changed.
02:59 Perfect. And that was repetition and concatenation. After building larger lists like this, it might be useful to reorder or even sort the new list. And you can see how in the next lesson.
Become a Member to join the conversation.