Find max length of list in list python

Last update on January 28 2021 09:39:46 [UTC/GMT +8 hours]

Write a Python program to find the list with maximum and minimum length.

Sample Solution:

Python Code:

def max_length_list[input_list]: max_length = max[len[x] for x in input_list ] max_list = max[input_list, key = len] return[max_length, max_list] def min_length_list[input_list]: min_length = min[len[x] for x in input_list ] min_list = min[input_list, key = len] return[min_length, min_list] list1 = [[0], [1, 3], [5, 7], [9, 11], [13, 15, 17]] print["Original list:"] print[list1] print["\nList with maximum length of lists:"] print[max_length_list[list1]] print["\nList with minimum length of lists:"] print[min_length_list[list1]] list1 = [[0], [1, 3], [5, 7], [9, 11], [3, 5, 7]] print["Original list:"] print[list1] print["\nList with maximum length of lists:"] print[max_length_list[list1]] print["\nList with minimum length of lists:"] print[min_length_list[list1]] list1 = [[12], [1, 3], [1, 34, 5, 7], [9, 11], [3, 5, 7]] print["Original list:"] print[list1] print["\nList with maximum length of lists:"] print[max_length_list[list1]] print["\nList with minimum length of lists:"] print[min_length_list[list1]]

Sample Output:

Original list: [[0], [1, 3], [5, 7], [9, 11], [13, 15, 17]] List with maximum length of lists: [3, [13, 15, 17]] List with minimum length of lists: [1, [0]] Original list: [[0], [1, 3], [5, 7], [9, 11], [3, 5, 7]] List with maximum length of lists: [3, [3, 5, 7]] List with minimum length of lists: [1, [0]] Original list: [[12], [1, 3], [1, 34, 5, 7], [9, 11], [3, 5, 7]] List with maximum length of lists: [4, [1, 34, 5, 7]] List with minimum length of lists: [1, [12]]

Pictorial Presentation:


Flowchart:


Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code [and comments] through Disqus.

Previous: Write a Python program to count number of lists in a given list of lists.
Next: Write a Python program to check if a nested list is a subset of another nested list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Merging two dictionaries in Python 3.5+ with a single expression:

Example:

import itertools tips_test = [[-1, -3], [50, 60], [15, 25]] print[list[itertools.chain.from_iterable[tips_test]]]

Output:

[-1, -3, 50, 60, 15, 25]

In this article, we will learn to find the longest string from a List in Python. We will use some built-in functions and some custom code as well. Let's first have a quick look over what is s list in Python.

Python List

Python has a built-in data type called list. It is like a collection of arrays with different methodology. Data inside the list can be of any type say, integer, string or a float value, or even a list type. The list uses comma-separated values within square brackets to store data. Lists can be defined using any variable name and then assigning different values to the list in a square bracket. The list is ordered, changeable, and allows duplicate values.

List Example

list1 = ["Ram", "Arun", "Kiran"] list2 = [16, 78, 32, 67] list3 = ["apple", "mango", 16, "cherry", 3.4]

Let us discuss two methods to find the longest string from a given Python List. The first method is a simple Brute Force Algorithm that uses for loop and another method uses built-in max[] function of Python List that returns a string of maximum length.

Example: Find Longest String from List using For Loop

This is a Brute Force Approach. It simply uses for loop to iterate over the elements of the given list. It checks the length of each string element and returns the string of maximum length.

#input list list1 = ['apple', 'banana', 'watermelon', 'orange'] max_len = -1 for ele in list1: if[len[ele] > max_len]: max_len = len[ele] res = ele print["Longest String is : ", res]


Longest String is : watermelon

Example: Find Longest String from List using max[] Function

This approach involves built-in max[] function to find maximum or longest string from the given Python List. max[] function takes two arguments, the iterable and other argument is key. Key = len to extract the string with the maximum length.

#input list list1 = ['apple', 'banana', 'watermelon', 'orange'] res = max[list1, key=len] print["Longest String is : ", res]


Longest String is : watermelon

Conclusion

In this article, we learned to find the longest string from the given Python List by using two methods. Firstly, we used for loop method and another was the max[] function. We used some custom code as well.

Use Python’s built-in max[] function with a key argument to find the longest string in a list. Call max[lst, key=len] to return the longest string in lst using the built-in len[] function to associate the weight of each string—the longest string will be the maximum.

Problem Formulation

Given a Python list of strings. Find the string with the maximum number of characters—the longest string in the list.

Here are a few example list of strings and the desired output:

# ['Alice', 'Bob', 'Pete'] ----> 'Alice' # ['aaa', 'aaaa', 'aa'] ----> 'aaaa' # [''] ----> '' # [] ----> ''

Solution: max[] function with key function argument len[]

Use Python’s built-in max[] function with a key argument to find the longest string in a list. Call max[lst, key=len] to return the longest string in lst using the built-in len[] function to associate the weight of each string—the longest string will be the maximum.

Here’s the code definition of the get_max_str[] function that takes a list of strings as input and returns the longest string in the list or a ValueError if the list is empty.

def get_max_str[lst]: return max[lst, key=len]

Here’s the output on our desired examples:

print[get_max_str[['Alice', 'Bob', 'Pete']]] # 'Alice' print[get_max_str[['aaa', 'aaaa', 'aa']]] # 'aaaa' print[get_max_str[['']]] # '' print[get_max_str[[]]] # ValueError

Border Case: What if the List is Empty?

If you want to return an alternative value in case the list is empty, you can modify the get_max_str[] function to include a second optional argument:

def get_max_str[lst, fallback='']: return max[lst, key=len] if lst else fallback print[get_max_str[[]]] # '' print[get_max_str[[], fallback='NOOOOOOOOO!!!!!!']] # NOOOOOOOOO!!!!!!

Solution with For Loop

A less Pythonic but, for beginner coders, more readable version is the following loop-based:

def get_max_str[lst, fallback='']: if not lst: return fallback max_str = lst[0] # list is not empty for x in lst: if len[x] > len[max_str]: max_str = x return max_str print[get_max_str[['Alice', 'Bob', 'Pete']]] # 'Alice' print[get_max_str[['aaa', 'aaaa', 'aa']]] # 'aaaa' print[get_max_str[['']]] # '' print[get_max_str[[], fallback='NOOOOOOOOO!!!!!!']] # NOOOOOOOOO!!!!!!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Video liên quan

Chủ Đề