  Python | Numbers in a list in a given range

Counters | Python Methods and Functions

After receiving the list, print the number of numbers in the specified range. Examples:

Input: [10, 20, 30, 40, 50 , 40, 40, 60, 70] range: 40-80 Output: 6 Input: [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 10-40 Output: 4

Multi-line approach:

Go through the list and check each number. If the number is in the specified range, then increase the counter. At the end of the traversal, the counter value will be the answer for the number of numbers in the specified range.

Below is a Python implementation of the above approach

 # Python program for counting # number of numbers in the given range # use of bypass code and double line   def count (list1 , l, r): c = 0   # move to list 1 for x in l ist1: # check status if x & gt; = l and x & lt; = r: c + = 1   return c   # driver code list1 = [ 10 , 20 , 30 , 40 , 50 , 40 , 40 , 60 , 70 ] l = 40 r = 80   print count (list1, l, r)

Exit :

6

Single line approach:

We can write one line to traverse and checks the condition together:

x for x in list1 if l & lt; = x & lt; = r

Return value (tr ue) the condition check is stored in the list and at the end the length of the list returns the response.

Below is the Python implementation of the above approach

 # Python program to count # number of numbers in the given range   def count (list1, l, r):   # x for x in list1 is the same as and traversing the list # if condition checks the number of numbers in the range # l to r # return temple is listed # whose response length return len ( list (x for x in list1 if l & lt; = x & lt; = r))   # driver code list1 = [ 10 , 20 , 30 , 40 , 50 , 40 , 40 , 60 , 70 ] l = 40 r = 80   print count (list1, l, r)

Exit:

6