Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check how many elements from a list fall within a specified range (Python)

Tags:

python

list

range

I have a list of elements (integers) and what I need to do is to quickly check how many elements from this list fall within a specified range. The example is below.

range is from 34 to 566

l = [9,20,413,425]

The result is 2.

I can of course use a simple for loop for the purpose and compare each element with the min and max value (34 < x < 566) and then use a counter if the statement is true, however I think there might be a much easier way to do this, possibly with a nice one-liner.

like image 869
WlJs Avatar asked May 16 '12 09:05

WlJs


People also ask

How do you find the number of elements in a range in Python?

The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.

How do you find out how many times an item is in a list in Python?

Using the count() Function The "standard" way (no external libraries) to get the count of word occurrences in a list is by using the list object's count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.

How do you check if an element is in a list more than once Python?

Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count().

How many items are in a list Python?

If a two-dimensional list (a list of lists) is passed directly to len() , the number of lists stored as elements is returned. The number of items in each list (the number of items in each row) can be obtained using the list comprehensions. The total number of items can be calculated with sum() .


3 Answers

>>> l = [9,20,413,425]
>>> sum(34 < x < 566 for x in l)
2
like image 131
Nolen Royalty Avatar answered Nov 13 '22 03:11

Nolen Royalty


len([x for x in l if x > 34 and x < 566])

like image 28
gefei Avatar answered Nov 13 '22 03:11

gefei


well i am not sure this is nice, but it's one line ;-)

len(set([9,20,413,425]).intersection(range(34,566)))
like image 41
snies Avatar answered Nov 13 '22 05:11

snies