Python | Numbers in a list within a given range
Given a list, print the number of numbers in the given 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
Multiple Line Approach:
Traverse in the list and check for every number. If the number lies in the specified range, then increase the counter. At the end of traversal, the value of the counter will be the answer for the number of numbers in specified range.
Below is the Python implementation of the above approach
# Python program to count the # number of numbers in a given range # using traversal and mutliple line code def count(list1, l, r): c = 0 # traverse in the list1 for x in list1: # condition check if x>= l and x<= r: c+= 1 return c # driver code list1 = [10, 20, 30, 40, 50, 40, 40, 60, 70] l = 40r = 80 print count(list1, l, r) |
Output:
6
Single Line Approach:
We can write a single line for traversal and checking condition together:
x for x in list1 if l <= x <= r
The return value(true) of the condition check is stored in a list, and at the end the length of the list returns the answer.
Below is the Python implementation of the above approach
# Python program to count the # number of numbers in a given range def count(list1, l, r): # x for x in list1 is same as traversal in the list # the if condition checks for the number of numbers in the range # l to r # the return is stored in a list # whose length is the answer return len(list(x for x in list1 if l <= x <= r)) # driver code list1 = [10, 20, 30, 40, 50, 40, 40, 60, 70] l = 40r = 80 print count(list1, l, r) |
Output:
6
Recommended Posts:
- Python | Generate random numbers within a given range and store in a list
- range() to a list in Python
- Python | Print list elements in circular range
- Python List Comprehension | Three way partitioning of an array around a given range
- Python program to print all even numbers in a range
- Python program to print all odd numbers in a range
- Python program to print all positive numbers in a range
- Python program to print all negative numbers in a range
- Python program to print odd numbers in a List
- Python | Multiply all numbers in the list (3 different ways)
- Python program to print even numbers in a list
- Python program to count Even and Odd numbers in a List
- Python | Make a list of intervals with sequential numbers
- Python program to print positive numbers in a list
- Python program to print negative numbers in a list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



