-1

Consider Below Code(Python)

  k=[45,51,66,11,99,44]
  z=k
  z.reverse()

Here Instead of Z the variable K also Reveresed

So What I need is only child variable z need to be reversed without modifying K variable (list)

1 Answers1

1
>>> k=[45,51,66,11,99,44]
>>> z = k[:]
>>> k.reverse()
>>> k
[44, 99, 11, 66, 51, 45]
>>> z
[45, 51, 66, 11, 99, 44]

This is a well known python behaviour and it has to do with its handling of references.

By doing z=k you're not saying "make a copy of k and assign it to z", but rather you're making both z and k point to the same object, or the same memory location. This has the implicit consequence that any change to z also affects k and vice versa. In other programming languages this behaviour is known as aliasing.

By using z=k[:] i'm using list slicing to explicitly create a new copy of z, and then assigning that new copy to k. That way, they're independent of one another and changes are not applied to both.

mencucci
  • 180
  • 1
  • 10