-1

I am using a recursive function on a list of lists with an accumulator, but instead of creating the right list of lists, it makes a list with duplicates of the last item inserted in the accumulator. I recreated the problem in a much simpler recursive function and list. This function takes a list of lists and makes 2 copies and reverses them n times.

def recursauto(x, n, instSet):
    #Base Case
    if(n==0):
        instSet.append(x)
        print(x) #Print to see what SHOULD be added
    else:
        temp = [x]*(2)  # Make a list with 2 copies of the original list
        for i in range(len(temp)):
            temp[i][i] = temp[i][i][::-1] # Make the list backwards
        for i in range(2):
            recursauto(temp[i], n-1, instSet) #Input each element

MyList = [] #Empyt list for accumulator
print("Correct output:")
recursauto([["A", "l", "e", "x"], ["A", "b", "d", "a", "l", "a", "h"]], 2, MyList)

print("Wrong printed list:")
for i in MyList:
    print(i) #Print what is in the accumulator

The output comes out wrong and the accumulator does not have the right things that were put into 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 that there is an easier way to do this, but the function I'm actually making requires recursion. Like I said, this is just a simplified recreation of the problem I am having.

1 Answers1

3
temp = [x]*(2)

The above line does not create a list of two copies of the original list; in fact, it just stores a reference to the same original list twice. If you want a distinct copy of x, try using the list copy constructor like temp = [list(x), list(x)] or alternatively the shallow copy method [x.copy() x.copy()].

See the below example.

>>> ls = ['a']
>>> dup = [ls] * 2
>>> dup
[['a'], ['a']]
>>> ls.append('b')
>>> dup
[['a', 'b'], ['a', 'b']]
obataku
  • 29,212
  • 3
  • 44
  • 57