I want to check the max length of array elements. Although I can do it with simple code, is there another smart way to implement this in Python 3?
a = [[1,2], [1], [2,2,3,3], [2,2]]
max_len = 0
for d in a:
max_len = len[d] if len[d] > max_len else max_len
print[max_len]
Mathias711
6,5024 gold badges40 silver badges57 bronze badges
asked Mar 16, 2017 at 7:01
2
You can do something like this:
max_len = max[[len[i] for i in a]]
print[max_len]
answered Mar 16, 2017 at 7:02
Mathias711Mathias711
6,5024 gold badges40 silver badges57 bronze badges
You can use the inbuilt max function:
>>> a = [[1,2], [1], [2,2,3,3], [2,2]]
>>> len[max[a, key=len]]
4
Mathias711
6,5024 gold badges40 silver badges57 bronze badges
answered Mar 16, 2017 at 7:03
HackaholicHackaholic
18.1k3 gold badges52 silver badges70 bronze badges
Given a list of lists, write a Python program to find the list with maximum length. The output should be in the form [list, list_length]. Examples:
Input : [['A'], ['A', 'B'], ['A', 'B', 'C']] Output : [['A', 'B', 'C'], 3] Input : [[1, 2, 3, 9, 4], [5], [3, 8], [2]] Output : [[1, 2, 3, 9, 4], 5]
Let’s discuss different approaches to solve this problem.
Approach #1 : Using for loop [Naive] This is a brute force method in which we iterate through each list item[list] and find the list with maximum length. Similarly, we use the for loop to find length of each list and output the maximum length.
Python3
def
FindMaxLength[lst]:
maxList
=
max
[[x]
for
x
in
lst]
maxLength
=
max
[
len
[x]
for
x
in
lst ]
return
maxList, maxLength
lst
=
[[
'A'
], [
'A'
,
'B'
], [
'A'
,
'B'
,
'C'
]]
print
[FindMaxLength[lst]]
Output:
[['A', 'B', 'C'], 3]
Time Complexity: O[N]
Auxiliary Space: O[1]
Approach #2: Using map In this method we use Python map function to iterate over the inner lists to create a list of lengths, then get the maximum with max function.
Python3
def
FindMaxLength[lst]:
maxList
=
max
[lst, key
=
len
]
maxLength
=
max
[
map
[
len
, lst]]
return
maxList, maxLength
lst
=
[[
'A'
], [
'A'
,
'B'
], [
'A'
,
'B'
,
'C'
], ]
print
[FindMaxLength[lst]]
Output:
[['A', 'B', 'C'], 3]
Time Complexity: O[N]
Auxiliary Space: O[N]
Approach #3: Using lambda operator One more method in Python to find the longest length list is the lambda operator. It is used for creating small, one-time and anonymous function objects in Python. Here we pass a variableias argument in the len[i] expression and find the maximum length.
Python3
def
FindMaxLength[lst]:
maxList
=
max
[lst, key
=
lambda
i:
len
[i]]
maxLength
=
len
[maxList]
return
maxList, maxLength
lst
=
[[
'A'
], [
'A'
,
'B'
], [
'A'
,
'B'
,
'C'
]]
print
[FindMaxLength[lst]]
Output:
[['A', 'B', 'C'], 3]
Time Complexity: O[N]
Auxiliary Space: O[1]