Open In App

Python – Test if List contains elements in Range

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A lot of times, while working with data, we have a problem in which we need to make sure that a container or a list is having elements in just one range. This has application in Data Domains. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using loop This is brute force method in which this task can be performed. In this, we just check using if condition if element falls in range, and break if we find even one occurrence out of range. 

Python3




# Python3 code to demonstrate
# Test if List contains elements in Range
# using loop
 
# Initializing loop
test_list = [4, 5, 6, 7, 3, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initialization of range
i, j = 3, 10
 
# Test if List contains elements in Range
# using loop
res = True
for ele in test_list:
    if ele < i or ele >= j :
        res = False
        break
 
# printing result
print ("Does list contain all elements in range : " + str(res))


Output : 

The original list is : [4, 5, 6, 7, 3, 9]
Does list contain all elements in range : True

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2 : Using all() This is alternative and shorter way to perform this task. In this we use check operation as a parameter to all() and returns True when all elements in range. 

Python3




# Python3 code to demonstrate
# Test if List contains elements in Range
# using all()
 
# Initializing loop
test_list = [4, 5, 6, 7, 3, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initialization of range
i, j = 3, 10
 
# Test if List contains elements in Range
# using all()
res = all(ele >= i and ele < j for ele in test_list)
 
# printing result
print ("Does list contain all elements in range : " + str(res))


Output : 

The original list is : [4, 5, 6, 7, 3, 9]
Does list contain all elements in range : True

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), as the code uses a constant amount of additional space regardless of the size of the input.

Method #3 : Using list comprehension and len()

This method uses a simple list comprehension which returns all elements which fall out of the given range. And then the length of this list is taken, if it is 0 that means all elements are in range and returns True, else returns False.

Python3




#Python3 code to demonstrate
#Test if List contains elements in Range
#using List Comprehension and len()
#Initializing list
test_list = [4, 5, 6, 7, 3, 9]
 
#printing original list
print("The original list is : " + str(test_list))
 
#Initialization of range
i, j = 3, 10
 
#Test if List contains elements in Range
#using List Comprehension and len()
out_of_range = len([ele for ele in test_list if ele < i or ele >= j])==0
 
#printing result
print ("Does list contain all elements in range : " + str(out_of_range))


Output

The original list is : [4, 5, 6, 7, 3, 9]
Does list contain all elements in range : True

Time complexity: O(n)
Auxiliary Space: O(n)

Method 4: Use the built-in set() function

Step-by-step approach:

  • Initialize a list test_list containing some elements.
  • Initialize two variables i and j to define a range.
  • Check if any element in test_list is within the range defined by i and j.
  • If any element is within the range, set the result res to True. Otherwise, set res to False.
  • Print the result of whether any element in the list is within the range.

Python3




# Python3 code to demonstrate
# Test if List contains elements in Range
# using any()
 
# Initializing list and range boundaries
test_list = [4, 5, 6, 7, 3, 9]
i, j = 3, 10
 
# Checking if any element in the list is within the range
res = any(i <= x < j for x in test_list)
 
# Printing the result
print("Does list contain any element in range: " + str(res))


Output

Does list contain any element in range: True

Time complexity: O(n), where n is the length of the list. 
Auxiliary space: O(1) because it only uses a few variables to store the range boundaries and the result.

Method 5: Using filter() function

Step-by-step approach:

  • Define a function that takes an integer x and returns True if it lies within the given range, i.e., i <= x < j.
  • Use the filter() function to filter out the elements of the list that satisfy the above condition.
  • Check if the filtered list is not empty using the bool() function.
  • Assign the result to a variable ‘res’.
  • Print the final result.

Python3




# Python3 code to demonstrate
# Test if List contains elements in Range
# using filter()
 
# Initializing list and range boundaries
test_list = [4, 5, 6, 7, 3, 9]
i, j = 3, 10
 
# Function to check if x lies within the given range
def in_range(x):
    return i <= x < j
 
# Filtering out the elements that lie within the range
filtered_list = list(filter(in_range, test_list))
 
# Checking if the filtered list is not empty
res = bool(filtered_list)
 
# Printing the result
print("Does list contain any element in range: " + str(res))


Output

Does list contain any element in range: True

Time complexity: O(n)
Auxiliary space: O(n) (to store the filtered list)



Similar Reads

Python - Test if elements of list are in Min/Max range from other list
Given two lists, the task is to write a Python Program to return true if all elements from second list are in range of min and max values of the first list. Examples: Input : test_list = [5, 6, 3, 7, 8, 10, 9], range_list = [4, 7, 9, 6] Output : True Explanation : Min and max in list 1 are 3 and 10, all elements are in range in other list. Input :
6 min read
Python | Test if string contains element from list
We are given a String and our task is to test if the string contains elements from the list. Example: Input: String: Geeks for Geeks is one of the best company. List: ['Geeks', 'for'] Output: Does string contain any list element : TrueNaive Approach checking each word in the string Here we are splitting the string into list of words and then matchi
8 min read
Python Check if the List Contains Elements of another List
In Python programming, there can be a case where we have to check whether a list contains elements of Another List or not. In that case, we can follow several approaches for doing so. In this article, we will be discussing several approaches to check whether a list contains elements of another list or not. Python List Contains Elements of another L
2 min read
Python - Test for all Even elements in the List for the given Range
Given a List of elements, test if all elements are even in a range. Input : test_list = [3, 1, 4, 6, 8, 10, 1, 9], i, j = 2, 5 Output : True Explanation : 4, 6, 8, 10, all are even elements in range. Input : test_list = [3, 1, 4, 6, 87, 10, 1, 9], i, j = 2, 5 Output : False Explanation : All not even in Range. Method #1: Using loop In this, we iter
2 min read
Python - Test if String contains any Uppercase character
Given a String, Test if it contains any uppercase character. Input : test_str = 'geeksforgeeks' Output : False Explanation : No uppercase character in String.Input : test_str = 'geeksforgEeks' Output : True Explanation : E is uppercase in String. Method #1 : Using loop + isupper() In this, we iterate for each character in String, check for uppercas
6 min read
Python | Test if dictionary contains unique keys and values
Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required, but as for values, we need to have ways to do it
6 min read
Python - Test if Tuple contains K
Sometimes, while working with Python, we can have a problem in which we have a record and we need to check if it contains K. This kind of problem is common in data preprocessing steps. Let’s discuss certain ways in which this task can be performed. Method #1: Using any() + map() + lambda Combination of above functions can be used to perform this ta
6 min read
Python | Test if String contains Alphabets and Spaces
Sometimes, while testing of credibility of string being a part of containing just alphabets, an exception of spaces has to be mentioned explicitly and becomes a problem. This can occur in domains that deal with data. Lets discuss certain ways in which this task can be performed. Method #1 : Using all() + isspace() + isalpha() This is one of the way
5 min read
Python | Check if list contains all unique elements
Some list operations require us to check if all the elements in the list are unique. This usually happens when we try to perform the set operations in a list. Hence this particular utility is essential at these times. Let's discuss certain methods by which this can be performed. Method #1: Naive Method Solutions usually start from the simplest meth
8 min read
Python - Filter the List of String whose index in second List contains the given Substring
Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
10 min read
Practice Tags :