w3resource

Python: Find the even-length words and sort them by length

Python Programming Puzzles: Exercise-50 with Solution

Write a Python program to find even-length words from a given list of words and sort them by length.

Input:
['Red', 'Black', 'White', 'Green', 'Pink', 'Orange']
Output:
['Pink', 'Orange']

Input:
['The', 'worm', 'ate', 'a', 'bird', 'imagine', 'that', '!', 'Absurd', '!!']
Output:
['!!', 'bird', 'that', 'worm', 'Absurd']

Visual Presentation:

Python: Find the even-length words and sort them by length.

Sample Solution:

Python Code:

# Define a function named 'test' that takes a list of words 'words' as input
def test(words):
    # Use a list comprehension to filter words with even lengths
    # Sort the filtered words first by length and then lexicographically
    return sorted([w for w in words if len(w) % 2 == 0], key=lambda w: (len(w), w))

# Assign a specific list of words to the variable 'words'
words = ["Red", "Black", "White", "Green", "Pink", "Orange"]
# Print a message indicating the original list of words
print("Original list of words:")
# Print the original list of words
print(words)
# Print a message indicating the even-length words sorting
print("Find the even-length words and sort them by length in the said list of words:")
# Print the result of the test function applied to 'words'
print(test(words))

# Assign another specific list of words to the variable 'words'
words = ['The', 'worm', 'ate', 'a', 'bird', 'imagine', 'that', '!', 'Absurd', '!!']
# Print a message indicating the original list of words
print("\nOriginal list of words:")
# Print the original list of words
print(words)
# Print a message indicating the even-length words sorting
print("Find the even-length words and sort them by length in the said list of words:")
# Print the result of the test function applied to 'words'
print(test(words))

Sample Output:

Original list of words:
['Red', 'Black', 'White', 'Green', 'Pink', 'Orange']
Find the even-length words and sort them by length in the said list of words:
['Pink', 'Orange']

Original list of words:
['The', 'worm', 'ate', 'a', 'bird', 'imagine', 'that', '!', 'Absurd', '!!']
Find the even-length words and sort them by length in the said list of words:
['!!', 'bird', 'that', 'worm', 'Absurd']

Flowchart:

Flowchart: Python - Find the even-length words and sort them by length.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Find the h-index, the largest positive number h such that h occurs in the sequence at least h times.
Next: Find the first n Fibonacci numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.