Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get complement (opposite) of list slice

Tags:

python

list

slice

Is there syntax to get the elements of a list not within a given slice? Given the slice [1:4] it's easy to get those elements:

>>> l = [1,2,3,4,5]
>>> l[1:4]
[2, 3, 4]

If I want the rest of the list I can do:

>>> l[:1] + l[4:]
[1, 5]

Is there an even more succinct way to do this? I realize that I may be being too needy because this is already very concise.

EDIT: I do not think that this is a duplicate of Invert slice in python because I do not wish to modify my original list.

like image 513
aberger Avatar asked Nov 09 '22 02:11

aberger


1 Answers

If you want to modify the list in-place, you can delete the slice:

>>> l = [1, 2, 3, 4, 5]
>>> del l[1:4]
>>> l
[1, 5]

Otherwise your originally suggestion would be the most succinct way. There isn't a way to get the opposite of a list slice using a single slice statement.

like image 180
Tyler Avatar answered Dec 08 '22 22:12

Tyler