Recursive function in Python does not change list -


this question has answer here:

i using recursive function on list of lists accumulator, instead of creating right list of lists, makes list duplicates of last item inserted in accumulator. recreated problem in simpler recursive function , list. function takes list of lists , makes 2 copies , reverses them n times.

def recursauto(x, n, instset):     #base case     if(n==0):         instset.append(x)         print(x) #print see should added     else:         temp = [x]*(2)  # make list 2 copies of original list         in range(len(temp)):             temp[i][i] = temp[i][i][::-1] # make list backwards         in range(2):             recursauto(temp[i], n-1, instset) #input each element  mylist = [] #empyt list accumulator print("correct output:") recursauto([["a", "l", "e", "x"], ["a", "b", "d", "a", "l", "a", "h"]], 2, mylist)  print("wrong printed list:") in mylist:     print(i) #print in accumulator 

the output comes out wrong , accumulator not have right things put it.

correct output: [['a', 'l', 'e', 'x'], ['a', 'b', 'd', 'a', 'l', 'a', 'h']] [['a', 'l', 'e', 'x'], ['a', 'b', 'd', 'a', 'l', 'a', 'h']] [['x', 'e', 'l', 'a'], ['h', 'a', 'l', 'a', 'd', 'b', 'a']] [['x', 'e', 'l', 'a'], ['h', 'a', 'l', 'a', 'd', 'b', 'a']] wrong printed list: [['x', 'e', 'l', 'a'], ['h', 'a', 'l', 'a', 'd', 'b', 'a']] [['x', 'e', 'l', 'a'], ['h', 'a', 'l', 'a', 'd', 'b', 'a']] [['x', 'e', 'l', 'a'], ['h', 'a', 'l', 'a', 'd', 'b', 'a']] [['x', 'e', 'l', 'a'], ['h', 'a', 'l', 'a', 'd', 'b', 'a']] 

i know there easier way this, function i'm making requires recursion. said, simplified recreation of problem having.

temp = [x]*(2) 

the above line not create list of 2 copies of original list; in fact, stores reference same original list twice. if want distinct copy of x, try using list copy constructor temp = [list(x), list(x)] or alternatively shallow copy method [x.copy() x.copy()].

see below example.

>>> ls = ['a'] >>> dup = [ls] * 2 >>> dup [['a'], ['a']] >>> ls.append('b') >>> dup [['a', 'b'], ['a', 'b']] 

Comments