Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Extract rows with Even length strings
When working with nested lists of strings, you may need to extract rows where all strings have even length. This can be accomplished using list comprehension with the all() function and modulus operator %.
Syntax
result = [row for row in nested_list if all(len(element) % 2 == 0 for element in row)]
How It Works
The solution uses three key components ?
-
len(element) % 2 == 0− Checks if string length is even -
all()− ReturnsTrueonly if all elements in the row have even length - List comprehension − Filters and collects rows that meet the condition
Example
data = [["python", "is", "best"], ["best", "good", "python"], ["is", "better"], ["for", "coders"]]
print("The list is:")
print(data)
result = [row for row in data if all(len(element) % 2 == 0 for element in row)]
print("The resultant list is:")
print(result)
The list is: [['python', 'is', 'best'], ['best', 'good', 'python'], ['is', 'better'], ['for', 'coders']] The resultant list is: [['python', 'is', 'best'], ['best', 'good', 'python'], ['is', 'better']]
Step-by-Step Analysis
Let's examine why each row is included or excluded ?
data = [["python", "is", "best"], ["best", "good", "python"], ["is", "better"], ["for", "coders"]]
for i, row in enumerate(data):
print(f"Row {i}: {row}")
lengths = [len(element) for element in row]
print(f"Lengths: {lengths}")
all_even = all(len(element) % 2 == 0 for element in row)
print(f"All even: {all_even}\n")
Row 0: ['python', 'is', 'best'] Lengths: [6, 2, 4] All even: True Row 1: ['best', 'good', 'python'] Lengths: [4, 4, 6] All even: True Row 2: ['is', 'better'] Lengths: [2, 6] All even: True Row 3: ['for', 'coders'] Lengths: [3, 6] All even: False
Alternative Approach Using Filter
You can also use the filter() function for the same result ?
data = [["python", "is", "best"], ["best", "good", "python"], ["is", "better"], ["for", "coders"]]
def has_all_even_lengths(row):
return all(len(element) % 2 == 0 for element in row)
result = list(filter(has_all_even_lengths, data))
print("Using filter():", result)
Using filter(): [['python', 'is', 'best'], ['best', 'good', 'python'], ['is', 'better']]
Conclusion
Use list comprehension with all() and modulus operator to extract rows where all strings have even length. This approach is both readable and efficient for filtering nested string lists.
Advertisements
