Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting list elements that aren't in a slice

Tags:

python

list

slice

Say I have a list

Q = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

I believe I can extract the first and every ninth value thereafter using the extended slice notation:

Q[::9]

Which should give:

[0,9,18]

But how can I similarly select all the elements apart from those?

like image 414
verdant Avatar asked Oct 16 '25 14:10

verdant


1 Answers

You mean this?

>>> lis = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
>>> lis[1::9]
[1, 10]

Extended slice notations:

lis[start : stop : step]  #default values : start = 0, stop = len(lis), step = 1

You can pass your own value for start(by default 0 be used)

Update:

>>> lis = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
>>> se = set(range(0, len(lis),9))   #use a list if the lis is not huge.
>>> [x for i,x in enumerate(lis) if i not in se]
[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17]

#for your example even this will work:
>>> [x for i,x in enumerate(lis) if i%9 != 0]
[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17]
like image 145
Ashwini Chaudhary Avatar answered Oct 18 '25 03:10

Ashwini Chaudhary



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!