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,568
  • 4
  • 41
  • 58
jef
  • 3,890
  • 10
  • 42
  • 76
  • 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

11

You can do something like this:

max_len = max([len(i) for i in a])
print(max_len)
Mathias711
  • 6,568
  • 4
  • 41
  • 58
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,568
  • 4
  • 41
  • 58
Hackaholic
  • 19,069
  • 5
  • 54
  • 72