Open In App

Python | Numbers in a list within a given range

Last Updated : 13 Apr, 2023
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.



Similar Reads

Python | Generate random numbers within a given range and store in a list
Given lower and upper limits, Generate random numbers list in Python within a given range, starting from 'start' to 'end', and store them in the list. Here, we will generate any random number in Python using different methods. Examples: Input: num = 10, start = 20, end = 40 Output: [23, 20, 30, 33, 30, 36, 37, 27, 28, 38] Explanation: The output co
5 min read
Python Program to replace list elements within a range with a given number
Given a range, the task here is to write a python program that can update the list elements falling under a given index range with a specified number. Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], i, j = 4, 8, K = 9 Output : [4, 6, 8, 1, 9, 9, 9, 9, 12, 3, 9, 1] Explanation : List is updated with 9 from 4th to 8th index. Input : test_
3 min read
Python | Find elements within range in numpy
Given numpy array, the task is to find elements within some specific range. Let's discuss some ways to do the task. Method #1: Using np.where() # python code to demonstrate # finding elements in range # in numpy array import numpy as np ini_array = np.array([1, 2, 3, 45, 4, 7, 810, 9, 6]) # printing initial array print(&quot;initial_array : &quot;,
2 min read
Python - Filter Strings within ASCII range
Given ASCII or alphabetical range, filter strings are found in a particular range. Input : test_list = ["gfg", "is", "best", "for", "geeks"], strt_asc, end_asc = 105, 115 Output : ['is'] Explanation : i has 105, and s has 115, which is in range ASCII values.Input : test_list = ["gfg", "is", "best", "for", "geeks"], strt_asc, end_asc = 100, 115 Outp
3 min read
Python | Count unique sublists within list
Given a list of lists, the task is to find the count of unique sublists within list. Examples: Input: [['Geek', 'for', 'geeks'], ['geeks', 'for'], ['for', 'Geeks', 'geek'], ['Geek', 'for', 'geeks']] Output: {('geeks', 'for'): 1, ('for', 'Geeks', 'geek'): 1, ('Geek', 'for', 'geeks'): 2} Below are some ways to achieve the task. Method #1: Using Itera
2 min read
Python | Create list of numbers with given range
Given two numbers r1 and r2 (which defines the range), write a Python program to create a list with the given range (inclusive). Examples: Input : r1 = -1, r2 = 1 Output : [-1, 0, 1] Input : r1 = 5, r2 = 9 Output : [5, 6, 7, 8, 9] Let's discuss a few approaches to Creating a list of numbers with a given range in Python. Naive Approach using a loop
5 min read
Python | Find missing numbers in a sorted list range
Given a range of sorted list of integers with some integers missing in between, write a Python program to find all the missing integers. Examples: Input : [1, 2, 4, 6, 7, 9, 10] Output : [3, 5, 8] Input : [5, 6, 10, 11, 13] Output : [7, 8, 9, 12] Method #1: List comprehension [GFGTABS] Python # Python3 program to Find missing # integers in list def
5 min read
Access object within another objects in Python
Prerequisite: Basics of OOPs in Python In this article, we will learn how to access object methods and attributes within other objects in Python. If we have two different classes and one of these defined another class on calling the constructor. Then, the method and attributes of another class can be accessed by first class objects ( i.e; objects w
2 min read
Import the Class within the Same Directory - Python
Python classes are the methods to use object-oriented programming in Python. Python allows to create classes in the main project we are working on or in a new file that only stores the class definition. This article will explain how to import a class within the same directory or subdirectory in Python. For this article, one does not need any Python
4 min read
Python - Accessing Items in Lists Within Dictionary
Given a dictionary with values as a list, the task is to write a python program that can access list value items within this dictionary. Method 1: Manually accessing the items in the list This is a straightforward method, where the key from which the values have to be extracted is passed along with the index for a specific value. Syntax: dictionary
5 min read
Practice Tags :