Python - Filter rows without Space Strings
Last Updated :
26 Apr, 2023
Given Matrix, extract rows in which Strings don't have spaces.
Examples:
Input: test_list = [["gfg is", "best"], ["gfg", "good"], ["gfg is cool"], ["love", "gfg"]]
Output: [['gfg', 'good'], ['love', 'gfg']]
Explanation: Both the lists have strings that don't have spaces.
Input: test_list = [["gfg is", "best"], ["gfg ", "good"], ["gfg is cool"], ["love", "gfg"]]
Output: [['love', 'gfg']]
Explanation: The list has strings that don't have spaces.
Method #1: Using list comprehension + any() + regex
In this, we check for no space in each string using regex, any() is used to check this for any string found with spaces, that row is not added.
Python3
# Python3 code to demonstrate working of
# Filter rows without Space Strings
# Using list comprehension + any() + regex
import re
# initializing list
test_list = [["gfg is", "best"], ["gfg", "good"],
["gfg is cool"], ["love", "gfg"]]
# printing original list
print("The original list is : " + str(test_list))
# checking for spaces using regex
# not including row if any string has space
res = [row for row in test_list if not any(
bool(re.search(r"\s", ele)) for ele in row)]
# printing result
print("Filtered Rows : " + str(res))
OutputThe original list is : [['gfg is', 'best'], ['gfg', 'good'], ['gfg is cool'], ['love', 'gfg']]
Filtered Rows : [['gfg', 'good'], ['love', 'gfg']]
Complexity Analysis:
Time Complexity: O(N2), (loop * re.search())
Auxiliary Space: O(N)
Method #2 : Using filter() + lambda + any() + regex
In this, we perform task of filtering using filter() and lambda function, rest all the functionalities are performed alike the above method.
Python3
# Python3 code to demonstrate working of
# Filter rows without Space Strings
# Using filter() + lambda + any() + regex
import re
# initializing list
test_list = [["gfg is", "best"], ["gfg", "good"],
["gfg is cool"], ["love", "gfg"]]
# printing original list
print("The original list is : " + str(test_list))
# checking for spaces using regex
# not including row if any string has space
res = list(filter(lambda row: not any(bool(re.search(r"\s", ele))
for ele in row), test_list))
# printing result
print("Filtered Rows : " + str(res))
OutputThe original list is : [['gfg is', 'best'], ['gfg', 'good'], ['gfg is cool'], ['love', 'gfg']]
Filtered Rows : [['gfg', 'good'], ['love', 'gfg']]
Complexity Analysis:
Time Complexity: O(N2), for loop takes the time complexity of O(n) and the filter also takes O(n) so together the final complexity is O(n2),
Auxiliary Space: O(N), the size of array, so O(n)
Method #3 : Using join() and find() methods
In this method, we perform task of joining all the strings using join() method and then checking if there is a space between the string using find() method.
Python3
# Python3 code to demonstrate working of
# Filter rows without Space Strings
# initializing list
test_list = [["gfg is", "best"], ["gfg", "good"],
["gfg is cool"], ["love", "gfg"]]
# printing original list
print("The original list is : " + str(test_list))
# checking for spaces using regex
# not including row if any string has space
res = []
for i in test_list:
a = "".join(i)
if(a.find(" ") == -1):
res.append(i)
# printing result
print("Filtered Rows : " + str(res))
OutputThe original list is : [['gfg is', 'best'], ['gfg', 'good'], ['gfg is cool'], ['love', 'gfg']]
Filtered Rows : [['gfg', 'good'], ['love', 'gfg']]
Time Complexity: O(n*n)
Auxiliary Space: O(n)
Method #4:Using itertools.filterfalse() method
Python3
# Python3 code to demonstrate working of
# Filter rows without Space Strings
import itertools
import re
# initializing list
test_list = [["gfg is", "best"], ["gfg", "good"],
["gfg is cool"], ["love", "gfg"]]
# printing original list
print("The original list is : " + str(test_list))
# checking for spaces using regex
# not including row if any string has space
res = list(itertools.filterfalse(lambda row: any(bool(re.search(r"\s", ele))
for ele in row), test_list))
# printing result
print("Filtered Rows : " + str(res))
OutputThe original list is : [['gfg is', 'best'], ['gfg', 'good'], ['gfg is cool'], ['love', 'gfg']]
Filtered Rows : [['gfg', 'good'], ['love', 'gfg']]
Time Complexity: O(N2)
Auxiliary Space: O(N)
Method #5: Here is a new approach using a list comprehension and the split and all() method:
Python3
# Python3 code to demonstrate working of
# Filter rows without Space Strings
# Using list comprehension + split() method
# initializing list
test_list = [["gfg is", "best"], ["gfg", "good"],
["gfg is cool"], ["love", "gfg"]]
# printing original list
print("The original list is : " + str(test_list))
# checking for spaces using the split() method
# not including row if any string has space
res = [row for row in test_list if all(ele.split() == [ele] for ele in row)]
# printing result
print("Filtered Rows : " + str(res))
OutputThe original list is : [['gfg is', 'best'], ['gfg', 'good'], ['gfg is cool'], ['love', 'gfg']]
Filtered Rows : [['gfg', 'good'], ['love', 'gfg']]
Time Complexity: O(N2), loop * split() method
Auxiliary Space: O(N)
Method #6: Using nested loops and flag variable
Step by step approach:
- Initialize a list of lists called test_list with some test data.
- Print the original list using the print() function and string concatenation.
- Initialize an empty list called res to store the filtered rows.
- For each row in test_list, do the following:
- Initialize a flag variable called flag to True.
- For each element (ele) in the current row, do the following:
- Check if the element contains any spaces using the in keyword and the string " " as a parameter. If it does, set the flag variable to False and break out of the loop using the break keyword.
- If the flag variable is still True after checking all elements in the current row, append the current row to the res list.
- Print the filtered rows using the print() function and string concatenation.
Python3
# Python3 code to demonstrate working of
# Filter rows without Space Strings
# Using nested loops and flag variable
# initializing list
test_list = [["gfg is", "best"], ["gfg", "good"],
["gfg is cool"], ["love", "gfg"]]
# printing original list
print("The original list is : " + str(test_list))
# removing rows containing space strings
res = []
for row in test_list:
flag = True
for ele in row:
if " " in ele:
flag = False
break
if flag:
res.append(row)
# printing result
print("Filtered Rows : " + str(res))
OutputThe original list is : [['gfg is', 'best'], ['gfg', 'good'], ['gfg is cool'], ['love', 'gfg']]
Filtered Rows : [['gfg', 'good'], ['love', 'gfg']]
Time complexity: O(n^2) (nested loop)
Auxiliary space: O(k) (where k is the length of the longest row)
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read