Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the length of an jagged array in python

I am trying to get the total no of items in my list which is updated from a SQLAlchemy command, it is a jagged array something like this..

list = [['linux'], ['ML'], ['linux', 'ML', 'Data Science', 'GIT'],['linux', 'Data Science', 'GIT'], ['GIT'], ['ML', 'GIT'], ['linux'], ['linux'], ['linux'], ['Data Science']]
length = len(list)

I get the output as: 10

How do I get the length as: 16 ? that is total no of items in the list ?

like image 727
Manoj Jahgirdar Avatar asked Jun 10 '18 07:06

Manoj Jahgirdar


People also ask

How do you find the length of a jagged array?

Firstly, declare and initialize a jagged array. int[][] arr = new int[][] { new int[] { 0, 0 }, new int[] { 1, 2 }, new int[] { 2, 4 }, new int[] { 3, 6 }, new int[] { 4, 8 } }; Now use the length property to get the length.

How do you find the length of an array in Python?

Use the len() method to return the length of an array (the number of elements in an array).

What do you mean by variable length array or jagged array?

A jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These types of arrays are also known as Jagged arrays.

What is jagged array in Python?

In computer science, a jagged array, also known as a ragged array, is an array of arrays of which the member arrays can be of different lengths, producing rows of jagged edges when visualized as output.


1 Answers

Don't use list, there's a builtin with that name already. I'll assume you meant "lst".

If your lists are small, use

>>> len(sum(lst, []))
16

Not recommended for large lists because list concatenation with sum is quadratic in time. However, this is really concise, so reconsider for small inputs.

If your lists are large (or have many elements), use

>>> sum(len(l) for l in lst)
16
like image 176
cs95 Avatar answered Oct 14 '22 08:10

cs95