0

In Python I have a list of numbers that have been added using .append(). I need to search my list to find if it contains any particular integer between two set values eg/ between 30 and 40.

I know I can use the code if x in n: to search a list for a single integer but I do not know how to do this for multiple integers.

intcreator
  • 4,206
  • 4
  • 21
  • 39
James Brightman
  • 857
  • 2
  • 13
  • 23

4 Answers4

3

Here's a function for you. It returns a list with all the values between the low and high limits given, including duplicates. If you want to get rid of duplicates, use set. I wouldn't sort it first because that would be less efficient than just iterating through the list.

def between(l1,low,high):
    l2 = []
    for i in l1:
        if(i > low and i < high):
            l2.append(i)
    return l2


l = [1,3,4,5,1,4,2,7,6,5] 

print( between(l,2,5) )

[3, 4, 4]

edit:

Or, hey, let's use list comprehension if you're into the whole brevity thing!

l = [1,3,4,5,1,4,2,7,6,5]
l2 = [i for i in l if i > 2 and i < 5]    
print(l2)

[3, 4, 4]

Charles Clayton
  • 17,005
  • 11
  • 87
  • 120
2

Some of above answers are efficient. I am just giving an approach with sorting the list.

filter(lambda x: x>30 and x<40,sorted(a))

a is input list

Vineesh
  • 253
  • 2
  • 7
0

Since you didn't provide any code yet, I'll give you a simple algorithm:

for every number in the list
    if the number is greater than 30 and less than 40
        do something with the number

For example, if you simply need to know if such a number exists, you can set a boolean value to true once the condition has been met.

This answer includes a more abbreviated way to accomplish what you have in mind.

Community
  • 1
  • 1
intcreator
  • 4,206
  • 4
  • 21
  • 39
0
min=30
max=40

nums = [8, 32, 35, 180]
nums.append(13)

for x in nums:
   if x > min and x < max: print x
  • 2
    `x > min and x < max` can be written more legible as `min < x < max` - does no one use chained comparisons? – AChampion Oct 14 '15 at 03:39