4

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,444
  • 4
  • 38
  • 54
jef
  • 3,601
  • 6
  • 35
  • 70
  • 3
    `max(len(x) for x in a)` or even shorter: `max(map(len,a))` – Julien Mar 16 '17 at 07:02
  • Possible duplicate of [Python's most efficient way to choose longest string in list?](http://stackoverflow.com/questions/873327/pythons-most-efficient-way-to-choose-longest-string-in-list) – Keerthana Prabhakaran Mar 16 '17 at 07:16

2 Answers2

10

You can do something like this:

max_len = max([len(i) for i in a])
print(max_len)
Mathias711
  • 6,444
  • 4
  • 38
  • 54
8

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,444
  • 4
  • 38
  • 54
Hackaholic
  • 17,534
  • 3
  • 51
  • 68