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']
Pictorial Presentation:

Sample Solution:
Python Code:
def test(words):
return sorted([w for w in words if len(w) % 2 == 0], key=lambda w: (len(w), w))
words = ["Red", "Black", "White", "Green", "Pink", "Orange"]
print("Original list of words:")
print(words)
print("Find the even-length words and sort them by length in the said list of words:")
print(test(words))
words = ['The', 'worm', 'ate', 'a', 'bird', 'imagine', 'that', '!', 'Absurd', '!!']
print("\nOriginal list of words:")
print(words)
print("Find the even-length words and sort them by length in the said list of 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:

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.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join