0

The following code was tried in a Python 2.7.1 interpreter.

>>> a = [1, 2, 3]
>>> a.append(a)
>>> a
[1, 2, 3, [...]]
>>> a == a[-1]
True
>>> print a[-1]
[1, 2, 3, [...]]

Can anyone please explain what python is trying to do here?

Aneesh Dogra
  • 740
  • 5
  • 30

3 Answers3

3

You have created an infinite nested list inside your list. As it can not be represented, [...] appears.

Take a look at what happens if you try to print each value:

>>> for item in a:
...     print item
... 
1
2
3
[1, 2, 3, [...]] # The whole list that we just iterated over :)

Refer to here for further reading.

Community
  • 1
  • 1
TerryA
  • 58,805
  • 11
  • 114
  • 143
2

Youre basically making a list of nested list (list within lists) and youre appending a list to itself creating a infinitely nested list

for example:

>>> a = [1,2,3]
>>> a.append(a)
>>> a
[1, 2, 3, [...]]
>>> 

>>> a[3]
[1, 2, 3, [...]]
>>> a[3][3]
[1, 2, 3, [...]]
>>> 

When you do a[3] its showing the next list in the nested list when i do a[3][3] Im getting the list within a[3] the [...] is how python portrays this idea

More information and example explaining these infinitely nested lists here

Serial
  • 7,925
  • 13
  • 52
  • 71
0

Lists are assigned as pointers to the original lists. If you truly want a list appended as element 3 you can make a copy like this:

>>> a.append(a[:])
>>> print a
[1, 2, 3, [1, 2, 3]]

or if you want the elements of a, instead use:

>>> a = a + a
>>> print a
[1, 2, 3, 1, 2, 3]
beroe
  • 11,784
  • 5
  • 34
  • 79