List & Tuple
Building Lists of Lists
Method 1
Create a list of three lists of three items each. Inspect the structure.
Place a mark in row 1, column 2, and check the result.
Method 2
The outer list is made of three references to the same inner list. While it is unchanged, all seems right.
Placing a mark in row 1, column 2, reveals that all rows are aliases referring to the same object.
Beware of expressions like a * n
when a
is a sequence containing mutable items because the result may surprise you.
For example, trying to initialize a list of lists as my_list = [ [] ]
*
3
will result in a list with three references to the same inner list, which is probably not what you want.
Augmented Assignment with Sequences
+=
and *=
operators produce very different results depending on the mutability of the target sequence
if __iadd__
is not implemented, Python falls back to calling __add__
-> a += b == a = a+b
.
Repeated concatenation of immutable sequences is inefficient, because instead of just appending new items. The interpreter has to copy the whole target sequence to create a new one with the new items concatenated.
There is one strange situation – tuple assignment puzzler,
Answer:
Playground
Last updated
Was this helpful?