0
def fun1(input):    
    input.reverse()       
    return input

this works fine for fun1([1,2,3])

but when i want to do something like this

input = [p,q,r]
print fun1(input)
print input

for both the above statements output is [r,q,p] but I want it to remain [p,q,r].

enter image description here

dr10
  • 11
  • 2
  • Do you want to reverse or not? What *exactly* is the expected output? –  Jun 25 '16 at 09:09
  • [`list.reverse` 'reverses the items of s in place'](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types). –  Jun 25 '16 at 09:12
  • i want to reverse the input and i want get the reversed output and initial input – dr10 Jun 25 '16 at 18:15

2 Answers2

1

Using input as a name will shadow the builtin input function, so that's a bad idea.

To keep input_ intact, you can modify a copy of it, instead of modifying it directly:

def fun1(input_):

      input_copy = input_[:] # A copy of input via slicing
      input_copy.reverse()
      return input_copy # return the mutated copy of your input

You can also use the explicit copy function to make a shallow copy:

input_copy = input_.copy()

Your input_ will not be modified and changes on the copy will not propagate to the original input_

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

Assign new local variable for the reversed list and return it:

def fun1(input):
    output = input[:]
return output.reverse()
Ami Hollander
  • 2,435
  • 3
  • 29
  • 47