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.
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.
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.
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().
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() .
>>> l = [9,20,413,425]
>>> sum(34 < x < 566 for x in l)
2
len([x for x in l if x > 34 and x < 566])
well i am not sure this is nice, but it's one line ;-)
len(set([9,20,413,425]).intersection(range(34,566)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With