Python | Check if Non-None values are contiguous
Last Updated :
02 Jun, 2023
Sometimes, while working with Python lists, we can have a problem in which we need to find if all the values that are valid (Non None). This has a lot of application in day-day programming. Let's discuss a method in which this task can be performed.
Method 1: Using iterator + all() + any() Combination of above functions can be used to perform this particular task. In this, we filter the leading None values using initial all(), then check for singular valid value sublist using any(), and then check for all the required None values. If any of the above return false. The Non-None values are not contiguous.
Python3
# Python3 code to demonstrate working of
# Check if Non-None values are contiguous
# Using iterator + all() + any()
# helper function
def check_cont(test_list):
test_list = iter(test_list)
all(x is None for x in test_list)
any(x is None for x in test_list)
return all(x is None for x in test_list)
# initializing list
test_list = [None, None, 'Gfg', 'is', 'Good', None, None, None]
# printing list
print("The original list : " + str(test_list))
# Check if Non-None values are contiguous
# Using iterator + all() + any()
res = check_cont(test_list)
# Printing result
print("Are non-none values contiguous ? : " + str(res))
OutputThe original list : [None, None, 'Gfg', 'is', 'Good', None, None, None]
Are non-none values contiguous ? : True
Time Complexity: O(n) where n is the number of elements in the list “test_list”. iterator + all() + any() performs n number of operations.
Auxiliary Space: O(1), constant extra space is required
Method 2: Using min(),max() and index() methods
Python3
# Python3 code to demonstrate working of
# Check if Non-None values are contiguous
# initializing list
test_list = [None, None, 'Gfg', 'is', 'Good', None, None, None]
# printing list
print("The original list : " + str(test_list))
# Check if Non-None values are contiguous
res=[]
for i in test_list:
if i is not None:
res.append(test_list.index(i))
mi=min(res)
ma=max(res)
x=[]
for i in range(mi,ma+1):
x.append(i)
res1=False
if(x==res):
res1=True
# Printing result
print("Are non-none values contiguous ? : " + str(res1))
OutputThe original list : [None, None, 'Gfg', 'is', 'Good', None, None, None]
Are non-none values contiguous ? : True
Method #3: Using Listcomprehension
- Define the check_cont() function that takes a list as input.
- Use a list comprehension to create a new list containing the indices of all non-None values in the input list.
- Use the zip() function to create pairs of adjacent indices in the new list.
- Use the all() function to check if the difference between each pair of adjacent indices is 1.
- Return the result of the all() function.
- Create a test list with some None and non-None values.
- Call the check_cont() function with the test list as input.
- Print the result of the function.
Python3
def check_cont(test_list):
# use a list comprehension to get the indices of all non-None values in the list
non_none = [i for i, x in enumerate(test_list) if x is not None]
# use the `zip()` function to create pairs of adjacent indices
# and check if the difference between them is always 1
return all(j-i == 1 for i, j in zip(non_none, non_none[1:]))
# create a test list with some None and non-None values
test_list = [None, None, 'Gfg', 'is', 'Good', None, None, None]
# call the function with the test list as input
res = check_cont(test_list)
# print the result
print("Are non-none values contiguous? : " + str(res))
#This code is contributed by Vinay pinjala.
OutputAre non-none values contiguous? : True
Time complexity: The list comprehension takes O(n) time to create a new list containing the indices of all non-None values in the input list. The zip() function and the all() function both iterate over this new list, which takes O(n) time. Therefore, the overall time complexity of this function is O(n).
Space complexity: The list comprehension creates a new list containing the indices of all non-None values in the input list, which takes O(k) space where k is the number of non-None values in the input list. The zip() function and the all() function both iterate over this new list, so they do not use any additional space. Therefore, the overall space complexity of this function is O(k).
Method#4:Using list slicing and the count() function
- Count the number of None values in the input list.
- If the count of None values is 0, return True, as all values are contiguous.
- If the count of None values is 1, return False, as there is only one non-None value and it cannot be considered contiguous
- Find the index of the first non-None value in the list.
- Find the index of the last non-None value in the list.
- Extract a slice of the list between the indices of the first and last non-None values.
- Count the number of None values in the extracted slice.
- If the count of None values in the slice is 0, return True, as all non-None values are contiguous. Otherwise, return False.
Python3
# Define a function to check if non-None values in a list are contiguous
def check_cont(test_list):
# Find the number of non-None values in the list
non_none_count = test_list.count(None)
# If there are no non-None values, return True
if non_none_count == 0:
return True
# If there is only one non-None value, return False
if non_none_count == 1:
return False
# Find the indices of the first and last non-None values in the list
start_index = test_list.index(next(val for val in test_list if val is not None))
end_index = len(test_list) - test_list[::-1].index(next(val for val in test_list[::-1] if val is not None)) - 1
# Check if the slice of the list between the first and last non-None values is all non-None
return test_list[start_index:end_index+1].count(None) == 0
# Define an input list containing None and non-None values
test_list = [None, None, 'Gfg', 'is', 'Good', None, None, None]
# Print the original list
print("The original list : " + str(test_list))
# Check if Non-None values are contiguous
# Using list slicing and the count() function
res = check_cont(test_list)
# Print the result
print("Are non-None values contiguous? : " + str(res))
OutputThe original list : [None, None, 'Gfg', 'is', 'Good', None, None, None]
Are non-None values contiguous? : True
The time complexity of this approach is O(n), where n is the length of the input list. This is because we need to iterate over the list to count the number of None values, find the indices of the first and last non-None values, and extract the slice of the list between those indices.
The auxiliary space complexity of this approach is O(1), as we are not using any additional data structures that scale with the size of the input.
Similar Reads
Python | Check if key has Non-None value in dictionary
Sometimes, while working with Python dictionaries, we might come across a problem in which we need to find if a particular key of the dictionary is valid i.e it is not False or has a non-none value. This kind of problem can occur in the Machine Learning domain. Let's discuss certain ways in which th
6 min read
Python | Check for None values in given dictionary
Many times, while working with dictionaries, we wish to check for a non-null dictionary, i.e check for None values in given dictionary. This finds application in Machine Learning in which we have to feed data with no none values. Let's discuss certain ways in which this task can be performed. Method
7 min read
Python | Check if all values are 0 in dictionary
While working with dictionary, we might come to a problem in which we require to ensure that all the values are 0 in dictionary. This kind of problem can occur while checking status of start or checking for a bug/action that could have occurred. Let's discuss certain ways in which this task can be p
7 min read
Python | Check if tuple has any None value
Sometimes, while working with Python, we can have a problem in which we have a record and we need to check if it contains all valid values i.e has any None value. This kind of problem is common in data preprocessing steps. Let's discuss certain ways in which this task can be performed. Method #1 : U
5 min read
Python - Check for None value in Matrix
Python supports a list as its list element and hence a matrix can be formed. Sometimes we might have a utility in which we require to perform None check in that list of list i.e matrix and its a very common in all the domains of coding, especially Data Science. Letâs discuss certain ways in which th
5 min read
Check if Value Exists in Python Dictionary
We are given a dictionary and our task is to check whether a specific value exists in it or not. For example, if we have d = {'a': 1, 'b': 2, 'c': 3} and we want to check if the value 2 exists, the output should be True. Let's explore different ways to perform this check in Python.Naive ApproachThis
2 min read
Python - Check if all elements in List are same
To check if all items in list are same, we have multiple methods available in Python. Using SetUsing set() is the best method to check if all items are same in list. Pythona = [3, 3, 3, 3] # Check if all elements are the same result = len(set(a)) == 1 print(result) OutputTrue Explanation:Converting
3 min read
Python | Check for None Tuple
Sometimes, while working with Python records, we can have a problem in which we need to filter out all the tuples which contain just None values. This can have a possible application in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using all() + gen
6 min read
Python - Check if Tuple contains only K elements
Sometimes, while working with Python tuples, we can have a problem in which we need to test if any tuple contains elements from set K elements. This kind of problem is quite common and have application in many domains such as web development and day-day programming. Let's discuss certain ways in whi
3 min read
Check if Tuple Exists as Dictionary Key - Python
The task is to check if a tuple exists as a key in a dictionary. In Python, dictionaries use hash tables which provide an efficient way to check for the presence of a key. The goal is to verify if a given tuple is present as a key in the dictionary.For example, given a dictionary d = {(3, 4): 'gfg',
3 min read