11

My tuple looks something like this(for a particular set of generated value)

tTrains = [ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]

Now, what I need to find is the length of longest tuple inside this tuple/list. I can always use a for loop, iterate over all the sub-tuples and do it. But I want to ask if there's a predefined function for the same.

Current Usage

This is what I am going to use as of now

max = 0
for i in range( len(tTrains) ):
  if iMax < len( i ):
    iMax = len( i )
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • 1
    The extra `,` in the tuples are actually important. A number in parenthesis is just a number, if you add the `,` it becomes a 1-item tuple. (I know it's not relevant for you anymore. Just in case somebody else needs it) – Mads Y Jan 28 '16 at 16:35

3 Answers3

15
tup=[ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]
max(map(len,tup))

result:

4
Max Li
  • 5,069
  • 3
  • 23
  • 35
  • thanks! ps today I looked for the first time at functional programming, this solution was inspired by it – Max Li Apr 07 '12 at 21:37
  • 1
    @JoelCornett no problem, I rejected the edit with the "custom" reason – Max Li Apr 07 '12 at 22:37
  • Link to the map function if you're not familiar with it: https://docs.python.org/2/library/functions.html#map – slm Feb 05 '15 at 20:17
8

You shouldn't use max as a variable name, since this will shadow the built-in of the same name. This built-in max() can be used to compute the maximum of an iterable.

You currently have a list of tuples, but you want the maximum of the list of their lengths. To get this list, you can use a list comprehension:

[len(t) for t in tuples]

(Note that I renamed your list tuple to tuples, since tuple would shadow the built-in type of the same name.)

Now you can apply max() to this list, or even better, to a generator expression constructed in a similar way.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • This was merely for question purpose. My actual variable names are like: `tScreens` for a tuple of screen and so one. Thanks. – hjpotter92 Apr 07 '12 at 21:21
8

Another solution:

>>> tup=[ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]
>>> len(max(tup, key=len))
4

which translates to 'give me the length of the largest element of tup, with "largest" defined by the length of the element'.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561