51. Problem to find the longest word in a set

In this Python set program, we will find the longest word in a set from a set of words with the help of the below-given steps.

What is set?
Sets are used to store multiple items in a single variable.
The set is one of 4 built-in data types in Python used to store collections of data.
It is an unordered collection data type that is iterable, mutable and has no duplicate elements.

Longest word in a set:

Steps to solve the program

1. Take a set of words.
2. Create two variables to store the word having maximum length and longest word in a set.
3. Assign their values equal to 0.
4. Use a for loop to iterate over words from the set.
5. Use an if statement with the len() function to check whether the length of the word is greater than the max_len variable.
6. If yes then assign the length of that word to max_len variable and word to max_word variable.
7. Print both the variables after loop is finished to see the result.

				
					Set = {"I","am","Learning","Python"}
max_len = 0
max_word = 0
print("Original Set: ",Set)
for word in Set:
    if len(word)>max_len:
        max_len =len(word)
        max_word = word
print("Word having maximum length: ",max_word)
print("Length of the word: ",max_len)
				
			

Output :

				
					Original Set:  {'Learning', 'am', 'Python', 'I'}
Word having maximum length:  Learning
Length of the word:  8
				
			

Related Articles

create two sets of books and find the intersection of sets.

Leave a Comment