Python Practice › File Handling Programs › Program 17
Odd and even length words
Write a Python program to put the words of a file into two lists by odd and even length.
Output
Even: ['Python', 'make', 'simple'] Odd: ['files', 'testing']
Approach
- Test
len(word) % 2.
Solution
with open("story.txt", "w") as f: f.write("Python files make testing simple\n") with open("story.txt") as f: words = f.read().split()print("Even:", [w for w in words if len(w) % 2 == 0])print("Odd:", [w for w in words if len(w) % 2 == 1])Output
Even: ['Python', 'make', 'simple'] Odd: ['files', 'testing']
Learn the concept
New to this topic? Read the lesson, then come back.