Odd and even length words

EasyFile Handling Programs · 17 of 38

Write a Python program to put the words of a file into two lists by odd and even length.

Advertisement
Output
Even: ['Python', 'make', 'simple']
Odd: ['files', 'testing']

Approach

  1. Test len(word) % 2.

Solution

Python
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']
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs