0

In this , I want to change first element of second nested list but.

L1=list('|  |')
L2=[L1,L1]
print L2

>>>[ [ '|', ' ', ' ', '|' ], [ '|', ' ', ' ', '|' ] ]

L2[1][0]='@'
print L2

>>>[ [ '@', ' ', ' ', '|' ], [ '@', ' ', ' ', '|' ] ]

Its Change both nested list!! Where I am going Wrong??

4 Answers4

2

I assume your second line is

L2 = [L1, L1]

By doing this, you do not pass L1 value to L2, but rather reference, twice. They point to the same place. id(L2[0][0]) and id(L2[1][0]) will give you the same.

An alternative

import copy
L2 = [L1, copy.copy(L1)]
Da Qi
  • 615
  • 5
  • 10
0

the problem is this:

L1 = list('|  |')
L2 = [L1, L1]

for item in L2:
    print(id(item))  # -> twice the same id.

you build a new list containing two references to the same list. changes to this list will be reflected in both items of L2.

what you probably want to do is this:

L2 = [list('|  |'), list('|  |')]

now

L2[1][0]='@'

works as expected.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0

When you create a list with two of the same list within it, you aren't creating two independent sublists - rather, you're creating a list with references to the same list in memory. Therefore, changing one, changes the other:

In [18]: L1=list('|  |')

In [19]: id(L1)
Out[19]: 4388545160

In [20]: L2 = [L1, L1]

In [21]: id(L2)
Out[21]: 4389336520

In [22]: for sub in L2: print(id(sub))
4388545160
4388545160

Your item reassignment is an in-place operation, which changes a sublist in memory, without reassigning it to something else. This leads to your behavior

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
0

Instead of working with the original list inside your second list, you can use list slicing to work with a copy of the original list. Take a look at the following examples for more details:

Without list slicing:

>>> l1 = ['a', 'b']
>>> l2 = [l1, l1]
>>>
>>> l2[1][0] = 'x'
>>> l2
[['x', 'b'], ['x', 'b']] # both sub-lists are changed

Now, with list slicing:

>>> l3 = ['a', 'b']
>>> l4 = [l3[:], l3[:]]
>>>
>>> l4[1][0] = 'x'
>>> l4
[['a', 'b'], ['x', 'b']]  # only the second sub-list is changed
ettanany
  • 19,038
  • 9
  • 47
  • 63