Problem 1: Write a python code that prints the longest word in the list of words?

What is a List in Python?

Lists: Lists in python are dynamic arrays that enable the user to store data belonging to any data type i.e int, string, float etc.
This characteristic of Lists makes it the most powerful tool in python. A list is ordered and always have a definite count.

The list is mutable data structure, which means it can be changed even after declaration.

A list in python is declared using square braces.

To print the longest word present in the list:

Step 1] We need to scan all the words present in the list. For this we initialize a for loop to iterate over the list. The loop will iterate for each word present in the list and calculate its length using the built in len() function.

Step 2] Once we scan the loop and find length of all words present in the list, we need to sort the list containing the lenths in ascending order. Thus the word having longest length will we present on the last index of list.

Step 3] Print the last item of list after sorting using the inbuilt sort function.

def find_longest_word(words_list):
    word_len = []
    for n in words_list:
        word_len.append((len(n), n))
    word_len.sort()
    return word_len[-1][1]

print(find_longest_word(["PHP", "ComputerTutor", "Backend"]))

As shown in the code snippet above, we have defined a function using keyword def which takes the words present in the list as a parameter. Another list names word_len is declared.  A for loop is initiated using n as a iterator which will scan the list passed as parameter.

It will initialize the list word_len which was declared and add to it the length of words present in list. The list is then sorted and last element of list is printed to give accurate output.

To view all the important questions click here.

You cannot copy content of this page