-2

Currently the output of below append cannot be used for practical purpose, This jira is to get the expectation for a case in append.

>>> a=[1,2]
>>> a.append(a)
>>> a
[1, 2, [...]]
>>>
  • 4
    What are you expecting to happen here, and what is wrong with what you get? – Daniel Roseman Dec 05 '18 at 19:41
  • It's not clear what you're asking for. Are you just trying to get the list "`[1,2,1,2]`" instead of the nested list "`[1, 2, [1,2] ]`"? If so, a simple `a+a` will do it. – Bill M. Dec 05 '18 at 19:44
  • @DanielRoseman thanks for the response, is there any Python documentation which explains this behaviour ? I understood the reason but I was expecting it to be [1,2,[1,2]] – Lingaraj Gowdar Dec 05 '18 at 20:45

2 Answers2

2

The third element is the entire list (i.e. a[2] is a, or id(a[2]) == id(a)). Because a contains itself, printing it would go on infinitely (a[2][2][2][2][2]...[2] == a), so the string conversion just gives you the "[...]" output.

manveti
  • 1,691
  • 2
  • 13
  • 16
0

The answer by Craig Meier explains why you're getting the output you're seeing. To eliminate the problem, make a copy of the list when you append it. A slice is the easiest way of copying a list.

>>> a=[1,2]
>>> a.append(a[:])
>>> a
[1, 2, [1, 2]]
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622