Skip to content Skip to sidebar Skip to footer

Regarding Python List With Reference

Here is the example, >>> x = ['a','b','c'] >>> yy = [x] * 3 >>> yy [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']] >>> yy[0][0] = 'A' >&g

Solution 1:

[x]*3 creates 3 references to the same list. You have to create three different lists:

>>> yy = [list('abc') for _ inrange(3)]
>>> yy[0][0]='A'>>> yy
[['A', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

The first line creates a new list using a list comprehension that loops 3 times.

Using id(), you can visualize that the same list reference is duplicated:

>>>x=list('abc')>>>id(x)
67297928                                  # list object id
>>>yy=[x]*3# create a list with x, duplicated...>>>[id(i) for i in yy]
[67297928, 67297928, 67297928]            # same id multipled
>>>yy = [list('abc') for _ inrange(3)]  >>>[id(i) for i in yy]
[67298248, 67298312, 67297864]            # three different ids

Post a Comment for "Regarding Python List With Reference"