1

When I write this code:

f=['a','b','c',['d','e','f']]
def j(f):
    p=f[:]
    for i in range(len(f)):
        if type(p[i]) == list:
            p[i].reverse()
    p.reverse()
    return p
print(j(f), f)

I expect that the result would be:

[['f', 'e', 'd'], 'c', 'b', 'a'] ['a', 'b', 'c', ['d', 'e', 'f']]

But the result I see is:

[['f', 'e', 'd'], 'c', 'b', 'a'] ['a', 'b', 'c', ['f', 'e', 'd']]

Why? And how can I write a code that do what I expect?

Arnold Schrijver
  • 3,588
  • 3
  • 36
  • 65
  • 2
    You were careful to copy the outer list, but this does not perform a _deep copy_ - the interior list is still referring to the same list as `f` inside your function. Take a look at [`copy.deepcopy`](https://docs.python.org/3/library/copy.html#copy.deepcopy). – miradulo Aug 06 '17 at 05:20
  • 1
    You are seeing a side-effect of the fact that [variables store references to lists, not the lists themselves](https://stackoverflow.com/questions/13530998/python-variables-are-pointers), so when you do `p[i].reverse()`, you are also reversing the list stored in `f` as well. – PaSTE Aug 06 '17 at 05:22

1 Answers1

-1

reverse modifies the list in place, you actually want to create a new list, so you don't reverse the one you've got, something like this:

def j(f):
    p=f[:]
    for i in range(len(f)):
        if type(p[i]) == list:
            p[i] = p[i][::-1]
    p.reverse()
    return p
Francisco
  • 10,918
  • 6
  • 34
  • 45