Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 list should be.

Inserting same list

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

Weirdly, I was getting the output

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

Inserting unique list

Now say I insert a unique list into layer1.

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

My output is as expected without ...

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

Desired output

How could I get this output using insert

[1, 2, [1, 2, 3, 4], 3, 4]
like image 940
Thavas Antonio Avatar asked Jan 30 '26 06:01

Thavas Antonio


1 Answers

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.

like image 140
Akshay Sehgal Avatar answered Jan 31 '26 22:01

Akshay Sehgal