-1
>>> def hello(l):
k=l
k.append('s')
return l

>>> hello(['hello'])
['hello', 's']

Just a strange occurrence i found in python3.4.1 I'm sure it has a reason but I don't understand it.

mikeLundquist
  • 769
  • 1
  • 12
  • 26
  • 1
    what do you mean redefining itself? What part of the result didn't you expect? – Anand S Kumar Aug 28 '15 at 15:38
  • Because changing a mutable object inside a function can impact the caller, and here you have create a reference to `l` with name `k` and change the `k` so actually you changed the `l`. – Mazdak Aug 28 '15 at 15:40
  • 1
    The variables `k` and `l` both refer to the same list, which you're modifying. – Barmar Aug 28 '15 at 15:40

1 Answers1

0

append modifies the referenced object in-place, instead or returning a new one. Even if you type k=l, the append method will modify the underlying referenced list, so both k and l will have the value ['hello', 's']

omu_negru
  • 4,642
  • 4
  • 27
  • 38