# Python – Filter rows without Space Strings

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

When it is required to filter rows without the soace strings, a list comprehension, regular expression, the ‘not’ operator and the ‘any’ method are used.

## Example

Below is a demonstration of the same

import re

my_list = [["python is", "fun"], ["python", "good"],["python is cool"],["love", "python"]]

print("The list is :")
print(my_list)

my_result = [row for row in my_list if not any(bool(re.search(r"\s", element)) for element in row)]

print("The resultant list is :")
print(my_result)

## Output

The list is :
[[‘python is’, ‘fun’], [‘python’, ‘good’], [‘python is cool’], [‘love’, ‘python’]]
The resultant list is :
[[‘python’, ‘good’], [‘love’, ‘python’]]

## Explanation

• The required packages are imported into the environment.

• A list of list is defined and is displayed on the console.

• A list comprehension is used to iterate over the list and the ‘search’ method from the regular expression is used to check for a string that doesn’t have space.

• The ‘any’ method and ‘not’ operator are used so that any of the strings could be filtered.

• This result is assigned to a variable.

• This is displayed as output on the console.

Updated on 14-Sep-2021 11:05:20