Search code examples
pythontraversalnested-lists

Python List of Lists traversing and updating


I am trying to change the element at the last index of list elements of z list but getting an error

l=['n1','n2','n3','n4']
path=['x','n1','y','z','n2']
y = ['n']
path+= y
d=0
seen = set()
for i in l:
   if i in path:
     f=0
   else:
      d+=1
      seen.add(i)


n=0
z = [[]]*d
for i in seen:
   z[n] = path
   z[n][-1] = i
   n+=1
print(z)

z should be

[['x', 'n1', 'y', 'z', 'n2', 'n3'], ['x', 'n1', 'y', 'z', 'n2', 'n4']] 

but its giving last index of list elements as n3 only i.e.,

 [['x', 'n1', 'y', 'z', 'n2', 'n3'], ['x', 'n1', 'y', 'z', 'n2', 'n3']] 

I am not able to figure out why it is not giving the correct result.


Solution

  • You assign a reference of path to z[n] in each of your iteration and make a change to the list's last element, so not only z[n] changes but also path gets the change. You should assign a copy of path to z[n] instead.

    Change:

    z[n] = path
    

    to:

    z[n] = path[:]