Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slicing insert question, L[1:1]

Tags:

python

slice

practising some python, which is a pretty easy language to grab up.

I have

>>> L = [1,2,3,4]
>>> L[1:1] = [1,2,3]
>>> L
[1, 1, 2, 3, 2, 3, 4]

so on line two actually L[1:1] is empty list, but how can python understand that insert the [1,2,3] list to starting from 1. I guess there is some internals which is not transparent to us, here apparently, I guess L[1:1] returns a reference to index 1 even if that returns an empty list...

Best wishes, Umut

like image 623
Umut Tabak Avatar asked Oct 20 '25 17:10

Umut Tabak


1 Answers

L[1:1] means the slice of the list L starting at index 1 (the second element), up to but not including index 1. So it is an empty list. On the right-hand side of an assignment, it is simply an anonymous empty list. But on the left-hand side, the assignment knows where the slice has been made, and can splice in the new list value into the proper place.

like image 196
Ned Batchelder Avatar answered Oct 23 '25 08:10

Ned Batchelder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!