How to Find List Element with Maximum Length in Python


In this example, we will learn how to pick out elements in the list that hold the maximum length with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def userList():
    n = int(input("Please input the number of elements: "))
    a = []
    for i in range(n):
        j = input("Please input the " + str(i + 1) + "th element: ")
        a.append(j)
    return a

a = userList()
max1 = max(a, key=len)
print("The element with maximum length is: ", max1)

Output:

Please input the number of elements: 4
Please input the 1th element: Green
Please input the 2th element: Red
Please input the 3th element: Purple
Please input the 4th element: Blue
The element with maximum length is: Purple
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement