indexed assignment in list

Peter Otten __peter__ at web.de
Wed Jul 11 02:54:26 EDT 2018


Abdur-Rahmaan Janhangeer wrote:

> saw this snippet on the internet : why assigning by index propagates it
> all?

It doesn't.

> 
>>>> a = [[1]] * 7
>>>> a
> [[1], [1], [1], [1], [1], [1], [1]]
>  >>> a[0][0] = 2
>>>> a
> [[2], [2], [2], [2], [2], [2], [2]]
> 
> why not
> 
> [[1], [2], [2], [2], [2], [2], [2]]

As to why you'd expect that one I've no idea.
 
> ?
> 
> thank you !

a = [[1]] * 7

creates a list containing seven references to the same inner list [1].

With seven distinct lists you get the expected

>>> a = [[1], [1], [1], [1], [1], [1], [1]]
>>> a[0][0] = 2
>>> a
[[2], [1], [1], [1], [1], [1], [1]]




More information about the Python-list mailing list