Python - Extract rows with Even length strings

Python - Extract rows with Even length strings

If you want to extract rows that contain even-length strings from a list, you can use list comprehensions. Here's how you can achieve this:

1. Sample Data:

For the sake of this tutorial, let's consider you have the following list of strings:

data = ["apple", "banana", "cherry", "kiwi", "mango", "peach", "pear"] 

2. Extract Rows with Even-Length Strings:

Using a list comprehension, you can identify and extract rows with even-length strings:

even_length_strings = [word for word in data if len(word) % 2 == 0] 

3. Display the Results:

Print the rows with even-length strings:

for word in even_length_strings: print(word) 

Output:

apple banana kiwi pear 

4. Working with a List of Lists:

If you have a list of lists (or a table-like structure) where each inner list has a string element, and you want to filter out the rows based on the length of these strings, you can adjust the approach accordingly.

For example:

table_data = [ [1, "apple"], [2, "banana"], [3, "cherry"], [4, "kiwi"], [5, "mango"], [6, "peach"], [7, "pear"] ] rows_with_even_length_strings = [row for row in table_data if len(row[1]) % 2 == 0] 

Then you can print the results:

for row in rows_with_even_length_strings: print(row) 

Output:

[1, 'apple'] [2, 'banana'] [4, 'kiwi'] [7, 'pear'] 

Summary:

In this tutorial, you learned how to extract rows with even-length strings from a list in Python. Using list comprehensions offers a concise and efficient method to filter out data based on specific criteria.


More Tags

katana multiprocessing phone-call formulas visual-studio-2012 pnp-framework pg-restore vetur meteor angular-ngselect

More Programming Guides

Other Guides

More Programming Examples