3

When I appended the list in itself using the following code.

a = [1, 2, 3, 4]
print a

a.append(a)
print a

I was expecting the output to be...

[1, 2, 3, 4]
[1, 2, 3, 4, [1, 2, 3, 4]]

But it was something like this...

[1, 2, 3, 4]
[1, 2, 3, 4, [...]]

WHY?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Heich-B
  • 672
  • 1
  • 6
  • 15

2 Answers2

10

You are adding a to a itself. The second element of a is a only. So, if it tries to print a, as you wanted

  • it would print the first element [1, 2, 3, 4]
  • it would print the second element, which is actually a

    • it would print the first element [1, 2, 3, 4]
    • it would print the second element, which is actually a

      • it would print the first element [1, 2, 3, 4]
      • it would print the second element, which is actually a ...

you see how it is going, right? It will be doing it infinitely. So when there is a circular reference like this, Python will represent that as an ellipsis within a pair of square brackets, [...], only.

If you want to insert a copy of a as it is, then you can use slicing to create a new list, like this

>>> a = [1, 2, 3, 4]
>>> a.append(a[:])
>>> a
[1, 2, 3, 4, [1, 2, 3, 4]]
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Does it mean that it is something like [1, 2, 3, 4, [1, 2, 3, 4, [1, 2, 3, 4, [...]]]] ? and can I use loop in it to get 'my expected results'? – Heich-B Mar 21 '15 at 13:17
  • @Myni The solution I suggested in my answer will give you the expected results. – thefourtheye Mar 21 '15 at 13:18
  • What does " (a[:]) " do, @thefourtheye ? – Heich-B Mar 21 '15 at 13:46
  • @Myni It will create a copy of the list `a`. It is called [slicing notation](http://stackoverflow.com/a/509295/1903116) – thefourtheye Mar 21 '15 at 13:47
  • I know that it is slicing notation, but what I meant was, what is ' a[:] ' exactly doing? – Heich-B Mar 21 '15 at 13:57
  • 1
    @Myni Normally slicing notations create a new list and return the sliced list. In this case, since the starting, ending and step are not mentioned, it will create a copy of the entire list. – thefourtheye Mar 21 '15 at 13:58
0

You could also add them using a for loop, But you end up with one big list.

a = [1, 2, 3, 4]

lengthOfA = len(a)

for x in range(0, lengthOfA):
    item = a[x]
    a.append(item)

print a #Answer is [1, 2, 3, 4, 1, 2, 3, 4]

I like this answer because it dosent create a nested list, But if that's not what you want please discard this answer.

If you want a list inside a list, You can use thefourtheye's awnser.

a = [1, 2, 3, 4]

a.append(a[:])

print a #Answer is [1, 2, 3, 4 [1, 2, 3, 4]]
Colourfit
  • 375
  • 3
  • 19