1

I just seen a output like below - just want to know what is happening here.

>>> l = [1,2,3,4]
>>> l[0]=l
>>> l
[[...], 2, 3, 4]

Why the l[0] value has displayed like this? Can anyone explain me why this behavior. I was thinking it'd return like, [[1,2,3,4], 2, 3, 4].

Cheers, Kalai

AKK
  • 21
  • 1
  • 5
  • Is this something with the actual address got assigned and turned to some wired output? Because, when I tried the below one, it's working fine. >>> l = [1,2,3,4] >>> l[1]=l[:] >>> l [1, [1, 2, 3, 4], 3, 4] – AKK Mar 10 '13 at 17:13
  • @Kalai: Does my answer explain? `l[:]` makes a copy of the list, otherwise it is still a pointer to the original. – David Robinson Mar 10 '13 at 17:18

3 Answers3

4

It shows the ... because otherwise it would have to infinitely recurse.

A list object in Python is a pointer to a list- assigning it like l[0] = l doesn't make a copy. For instance, try

l1 = [1, 2, 3, 4]
l2 = [1, 2]
l2[0] = l1
print l2
# [[1, 2, 3, 4], 2]
l2[0].append(5)
print l1
# [1, 2, 3, 4, 5]

Notice that even though you never changed l1 explicitly, it has now been appended to.

Therefore, when you place a list within itself, that item of the list is still a link to the entire list. After your code above, try doing:

l[1]  # ==> 2
l[0][1]  # ==> 2
l[0][0][1]  # ==> 2
David Robinson
  • 77,383
  • 16
  • 167
  • 187
2

Use a copy of the list to avoid infinite recursion:

In [10]: l = [1,2,3,4]

In [11]: l[0] = l[:]

In [12]: l
Out[12]: [[1, 2, 3, 4], 2, 3, 4]
root
  • 76,608
  • 25
  • 108
  • 120
0

If you would have used a PrettyPrinter, the output would had been self explanatory

>>> l = [1,2,3,4]
>>> l[0]=l
>>> l
[[...], 2, 3, 4]
>>> pp = pprint.PrettyPrinter(indent = 4)
>>> pp.pprint(l)
[<Recursion on list with id=70327632>, 2, 3, 4]
>>> id(l)
70327632
Abhijit
  • 62,056
  • 18
  • 131
  • 204