0

I have encountered this function:

    def square_it(var):
    return [var *2] *2

zoo = (square_it([1]))
zoo[1][0] +=1
print(zoo)

I dont understand why the output is: [[2, 1],[2,1]] and not [[1, 1], [2, 1]] can someone please explain this? Thanks.

Efrat.shp
  • 117
  • 1
  • 9
  • 2
    `[var *2] *2` is returning a list of the same element twice... – MooingRawr Mar 02 '18 at 18:23
  • so do you mean both elements have the same address when you multiply a list? – Efrat.shp Mar 02 '18 at 18:24
  • 2
    Give the dup link a read, it's the same issue you have, basically if you look at the memory location of both sub lists, you will see that they are the same object, using the same memory – MooingRawr Mar 02 '18 at 18:25
  • 1
    `square_it` returns a list with 2 elements that is the same object. lets assume that `var *2` is object `A` (equals to `[1, 1]`) then `[var *2] *2` is `[A, A]` later you are accessing the function result as `zoo[1]`. that would be `A`. try to check `zoo[0] is zoo[1]`. That is the same object – Ev_genus Mar 02 '18 at 18:29
  • 1
    @Efrat.shp it is generally not very helpful to think about addresses in Python. Suffice it to say, *they are the same object*. I.E. `zoo[0] is zoo[1]` – juanpa.arrivillaga Mar 02 '18 at 18:31

0 Answers0