Open In App

Python | Numbers in a list within a given range

Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python program to count the
# number of numbers in a given range
# using traversal and multiple 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 = 40
r = 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




# 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 = 40
r = 80
print count(list1, l, r)


Output

6

Approach#3 : Using sum We can use sum in this  problem. We use list comprehension to iterate over the list and check number is in range or not if it is present comparison will have 1 as have else 0 as value. Sum function return the sum of total of parameters.

Python3




# Python program to count the
# number of numbers in a given range
 
def count(list1, l, r):
     
    # Traversing the list with on line for loop
    # check if number is in range of not
    return sum( l <= x <= r for x in list1)
 
# driver code
list1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]
l = 40
r = 80
print( count( list1, l, r ) )


Output

6

Using the built-in function filter():

 This function takes a function and an iterable as arguments and returns a new iterable containing only the elements for which the function returns True.

To count the number of numbers in the given range, we can define a lambda function that checks if a number is in the range, and then pass this function to filter() along with the list. The length of the resulting iterable will be the number of numbers in the range.

Here is an example of how to use this approach:

Python3




def count(list1, l, r):
    return len(list(filter(lambda x: l <= x <= r, list1)))
 
list1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]
l = 40
r = 80
print(count(list1, l, r))


Output

6

This will output 6, as in the other solutions.

The time complexity of this approach is O(n), where n is the length of the list, and the space complexity is O(n), since filter() creates a new iterable containing all the elements that satisfy the condition.

Approach#4: Using List Comprehension

step-by-step algorithm for implementing the approach:

  1. Define a function named count that takes three arguments: a list list1 and two integers l and r.
  2. Inside the function, use a list comprehension to filter elements within the range l and r (inclusive) from list1.
  3. Return the length of the resulting list.
  4. Define a list named list1 with some elements.
  5. Define two integers l and r that define the range of elements we are interested in.
  6. Call the count function with the arguments list1, l, and r.
  7. Print the list, range, and the count of elements within the range.

Python3




# Function to count the number of elements in a given range
def count(list1, l, r):
    # Using list comprehension to filter elements within the range
    # and returning the length of the resulting list
    return len([x for x in list1 if x >= l and x <= r])
 
# Example usage
list1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]
l = 40
r = 80
count_of_elements = count(list1, l, r)
print("The list is:", list1)
print("The number of elements between", l, "and", r, "is:", count_of_elements)


Output

The list is: [10, 20, 30, 40, 50, 40, 40, 60, 70]
The number of elements between 40 and 80 is: 6

 Time Complexity:

The time complexity of this approach is O(n) where n is the length of list1. This is because the list comprehension is iterating through all the elements in list1 and filtering out the elements that fall within the given range.
Auxiliary Space:

The auxiliary space complexity of this approach is O(k), where k is the number of elements in list1 that fall within the given range. This is because we are creating a new list using a list comprehension to store the filtered elements. However, since k ? n, the space complexity can be considered as O(n).

Approach#5: Using bisect module

The bisect module in Python provides support for binary search through a sorted list. We can use this module to count the number of numbers in a given range in a sorted list efficiently.

Here is the algorithm using the bisect module:

Sort the input list using the sorted() function in Python.
Use the bisect_left() and bisect_right() functions from the bisect module to find the index of the leftmost and rightmost occurrence of the range limits in the sorted list, respectively.
Calculate the count of numbers in the range by taking the difference of the two indices found in the previous step.
Return the count.
Here is the Python code implementing the above algorithm:

Python3




import bisect
  
def count(list1, l, r):
    # sort the list
    list1.sort()
  
    # find the index of leftmost occurrence of l in list1
    left_idx = bisect.bisect_left(list1, l)
  
    # find the index of rightmost occurrence of r in list1
    right_idx = bisect.bisect_right(list1, r)
  
    # calculate the count of numbers in the range
    count = right_idx - left_idx
  
    return count
  
# driver code
list1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]
l = 40
r = 80
print(count(list1, l, r))    # Output: 6


Output

6

The time complexity of this algorithm is O(log n) for both the sorting and the bisect functions. The auxiliary space is O(1) as we are not creating any new data structure or using any extra memory.



Last Updated : 13 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads