In this python file program, we will get all odd and even length words in two lists with the help of the below-given steps.. Let’s consider we have readcontent.txt file with the below content.
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is Africa.
Line6 : This is Korea.
Line7 : This is Germany.
Line8 : This is China.
Steps to solve the program
- Open the first file by using open(“readcontent.txt”).
- Read the data and split it into words using file.read().split().
- Create two empty lists even and odd.
- Use a for loop to iterate over the words.
- If the length of the word is even then add it to the even list, else add it to the odd list.
- Use an if-else statement for this purpose.
- Print the output.
# Open the file
file = open('readcontent.txt')
# Convert data into words
words = file.read().split()
# Create empty lists
even = []
odd = []
# Iterate over words
for word in words:
# Check for odd,even words
# Add them to corresponding list
if len(word)%2==0:
even.append(word)
else:
odd.append(word)
# Print output
print("Words having even length: ",even)
print("Words having odd length: ",odd)
Output :
Words having even length:
[‘This’, ‘is’, ‘India.’, ‘This’, ‘is’, ‘America.’, ‘This’, ‘is’, ‘This’, ‘is’, ‘Australia.’, ‘This’, ‘is’, ‘This’, ‘is’, ‘Korea.’, ‘This’, ‘is’, ‘Germany.’, ‘This’, ‘is’, ‘China.’]
Words having odd length:
[‘Line1’, ‘:’, ‘Line2’, ‘:’, ‘Line3’, ‘:’, ‘Canada.’, ‘Line4’, ‘:’, ‘Line5’, ‘:’, ‘Africa.’, ‘Line6’, ‘:’, ‘Line7’, ‘:’, ‘Line8’, ‘:’]