简体   繁体   中英

Why does appending a list to itself show […] when printed?

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?

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]]

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM