Skip to content Skip to sidebar Skip to footer

Removing Range Of Items From A List

Is there a way to remove items in a range in list? For example: a = [1,2,3,4,5]. How to remove items from 3 to 5?

Solution 1:

Something like this should do the trick

[z for z in [1,2,3,4,5,6,7] ifnot3<=z<=5]


Out[2]:
[1, 2, 6, 7]

If you want to make it more flexible can replace with variables depending on your needs which is simply done:

alist=[1,2,3,4,5,6,7]
lowerbound=3upperbound=5resultlist=[z for z in alist if not lowerbound<=z<=upperbound]
#result you want stored as 'resultlist'

Solution 2:

Yes, you can use a list comprehension to filter the data.

a = [1,2,3,4,5]
print([x for x in a if 3 <= x <= 5])

Post a Comment for "Removing Range Of Items From A List"