Catching more items in a list array in Python

4

I have an array in Python made up of arrays. But these arrays can have different sizes. For example:

matriz = [[1,2,3],[4,5,6,7],[1,2,3,4,5,6]]

What I want to know is if there is a medium (some python-ready function) that returns the size of the largest array in that array.

For example:

x = funcao(matriz)

which would return to x the value 6 (array size at array position 3).

    
asked by anonymous 07.12.2016 / 14:51

3 answers

6

You can iterate through your array by creating a generator and using a len() to get the size of each element, like this: gen = (len(x) for x in matriz) and then use the max() function to get the largest element of the generator.

Example:

matriz = [[1,2,3],[4,5,6,7],[1,2,3,4,5,6]]
gen = (len(x) for x in matriz)
print(type(gen))
print(max(gen))

Output:

  

<class 'generator'>
  6

See working at ideone

    
07.12.2016 / 15:02
5

Other version:

max(map(len,matriz))
    
07.12.2016 / 18:39
5

Use max:

matriz = [[1,2,3],[4,5,6,7],[1,2,3,4,5,6]]
len_maior = len(max(matriz, key=len)) # tamanho da maior sublista, 6

max(matriz, key=len) will return the highest sublist ( [1,2,3,4,5,6] ), based on its len (size), then we will actually 'measure it' and know its size ( len([1,2,3,4,5,6]) ), which is 6 in this case

DEMONSTRATION

    
07.12.2016 / 15:02