Home > OS >  reverse list and append it to istelf
reverse list and append it to istelf

Time:12-01

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"]

CodePudding user response:

You can use slicing:

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

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

The 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() reverts the list in place. These two lines of code, therefore, reverts the list list (as well as reversel). As a result, now list and reversel both become ["beta", "alpha"]. Then after list.extend(reversel), list becomes what you observe.

Also, there is another subtle issue; it is not generally recommended to do 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 either 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).

CodePudding user response:

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.

CodePudding user response:

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))
  • Related