-1

could someone explain me why my python code print this [...] what does it mean ? Thank you

My code:

def foo(x,y): 
    x[0]= y[1]
    x,y=y,x
    return x+y
z=[1,2]
z2=[z,z]
t=foo(z,z2)
print(z)
print(z2)
print(t)
  • It's because the list references itself. Try this: `x = [1,2,3]` then `x[2] = x` then `print(x)`, `print(x[2])`, `print(x[2][2])`, `print(x[2][2][1])` – juanpa.arrivillaga Aug 18 '16 at 07:14

1 Answers1

0

This is because z list is referencing itself at [0] location, when you do this:

def foo(x,y): 
    x[0]= y[1]
    x,y=y,x
    return x+y
z=[1,2]
#Here you have created a list containing 1,2 
z2=[z,z]
#here is not creating two lists in itself, but it is referencing z itself(sort of like pointer), you can verify this by:
In [21]: id(z2[0])
Out[21]: 57909496
In [22]: id(z2[1])
Out[22]: 57909496
#see here both the location have same objects
t=foo(z,z2)
#so when you call foo and do x[0]= y[1], what actually happens is  
# z[0] = z2[0] , which is z itself
# which sort of creates a recursive list
print(z)
print(z2)
print(t)
#you can test this by
In [17]: z[0]
Out[17]: [[...], 2]
In [18]: z[0][0]
Out[18]: [[...], 2]
In [19]: z[0][0][0]
Out[19]: [[...], 2]
In [20]: z[0][0][0][0]
Out[20]: [[...], 2]
#you can carry on forever like this, but since it is referencing itself, it wont see end of it
shaktimaan
  • 1,769
  • 13
  • 14