Home > front end >  How to extract elements in an array according to some boundaries in Python?
How to extract elements in an array according to some boundaries in Python?

Time:05-28

I have an array like x = [3, 5, 6, 11, 18, 24, 29] I want to extract the elements which are greater than 5 and less than or equal to 24 from x.

How can i do that?

CodePudding user response:

x = [3, 5, 6, 11, 18, 24, 29]
selected = [i for i in x if i>5 and i<=24]
print(selected)

CodePudding user response:

If you use/prefer numpy, you can use np.where():

x[np.where((x > 5) & (x <= 24))]

or just:

x[(x > 5) & (x <= 24)]

result:

array([ 6, 11, 18, 24])

CodePudding user response:

If all you need to do is to extract all the elements/numbers that are greater than 5 and less than 24, you'll have to use for/while loops.

for your problem it's best to use a for loop, so the code will look something like this:

x = [3, 5, 6, 11, 18, 24, 29]
new_lst = []

for number in x:
    if number > 5 and number < 24:
        new_lst.append(number)

You can read about the .append() function here.

  • Related