1

Im trying to get a list to inputted in a function, and then the output would be the list, and then the reverse of the list added onto itself but for some reason whenever I reverse the variable reversal, it reverses list as well

def mirror(list):
    reversel = list
    reversel.reverse()
    list.extend(reversel)
    return list

    
    
    
test = ["alpha", "beta"]
print(mirror(test))

output

['beta', 'alpha', 'beta', 'alpha']

desired output

["alpha","beta","beta","alpha"]
Keegry
  • 33
  • 2

4 Answers4

4

You can use slicing:

def mirror(lst):
    return lst + lst[::-1]

test = ["alpha", "beta"]
print(mirror(test)) # ['alpha', 'beta', 'beta', 'alpha']

An issue in the provided code is that (i) reversel = list (but don't use list as a name) does not copy the object, and (ii) reverse() reverses the list in place. These two lines of code, therefore, reverse the list list (as well as reversel). As a result, now list and reversel both are ["beta", "alpha"]. Then after list.extend(reversel), list becomes what you observe.

Also, there is another subtle issue; it is not generally recommended doing both of the following: (i) modify a given object, and (ii) return the object; this might cause confusion (I believe). It is better to do only one of them; modify an object in place (like reverse), or don't modify the object but return a modified copy of the object (like reversed).

j1-lee
  • 13,764
  • 3
  • 14
  • 26
0

This should work -

def mirror(list):
    reversel = [i for i in list]
    reversel.reverse()
    list.extend(reversel)
    return list

    
    
    
test = ["alpha", "beta"]
print(mirror(test))

when using '=' it stores the location of the variable. So when using a function like reverse, both values change.

sr0812
  • 324
  • 1
  • 9
0

Here is a solution without using reverse().

def mirror(list_to_mirror):
    
    reversel = list_to_mirror
    reversel = reversel[::-1]
    #This is an equivilant to reverse()
    list_to_mirror.extend(reversel)
    
    return list_to_mirror

if __name__ == "__main__":
    test = ["alpha", "beta"]
    print(mirror(test))
Enderbyte09
  • 409
  • 1
  • 5
  • 11
  • You make this overly complex by introducing the `reversel` variable. Just drop the first to code lines in the function and use `list_to_mirror.extend(list_to_mirror[::-1])`. – Matthias Dec 01 '21 at 07:33
-1

A way that doesn't require creating and discarding a copy:

def mirror(lst):
    lst += reversed(lst)
    return lst
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65