Skip to content Skip to sidebar Skip to footer

Ellipsis When Inserting List Into Same List

I was trying to find a solution to a question when I came across this problem. I was trying to insert a list into the same list using insert. But I'm getting a ... where the new li

Solution 1:

Reason for the ellipsis

You are trying to insert the object into itself at position 2 (len(layer1)//2). You can consider the ellipsis (...) as a pointer to the object itself.

The str / repr functions have been protected against this to avoid infinite recursion, and show an ellipsis instead (...). Refer this.

It's not possible to print an object which has been modified with the insertion of itself, as it would enter infinite recursion. Think about it, if you modify the list by inserting itself into it, the new updated list that you are referring to would be inserted into itself as well, since you are only pointing to the object.

This becomes apparent if you try to access the ellipsis object in the list -

layer1 = [1,2,3,4]
layer1.insert(len(layer1)//2,layer1)print('list:',layer1)
print('ellipsis:', layer1[2])
list: [1, 2, [...], 3, 4]ellipsis: [1, 2, [...], 3, 4]

Any update in the original list also must reflect in the inserted item and vice versa. Therefore it's displayed as an ellipsis instead.


Resolving the print

A way to resolve this would be using a copy -

layer1 = [1,2,3,4]
layer1.insert(len(layer1)//2,layer1[:]) #<--- slicing returns copy
layer1
[1, 2, [1, 2, 3, 4], 3, 4]

Details here.

Solution 2:

When you insert [1, 2, 3, 4] into itself, what you really have is:

layer1 = [1, 2, layer1, 3, 4]

If you "open" layer1 (the dots) to see what's in it, you get:

layer1 = [1, 2, [1, 2, layer1, 3, 4], 3, 4]

As you can see, this will go on forever. The list is "self-referential", it refers to itself.

Instead, you would need to make a copy of the list.

layer1 = [1,2,3,4]
layer1.insert(len(layer1)//2,layer1.copy())

Solution 3:

You are creating a self-referencing list by inserting a list to itself. It's like a while(1) without any break.

Maybe you can use this for achieving your purpose:

layer1 = [1,2,3,4]
layer1.insert(len(layer1)//2,layer1[:])

Post a Comment for "Ellipsis When Inserting List Into Same List"