Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of 2d list in python

I have a 2D list, for example mylist =[[1,2,3],[4,5,6],[7,8,9]].

Is there any way I can use len() function such that I can calculate the lengths of array indices? For example:

len(mylist[0:3])
len(mylist[1:3])
len(mylist[0:1])

Should give:

9
6
3
like image 320
ranger Avatar asked Aug 04 '13 05:08

ranger


People also ask

What is the length of a 2D array?

The length of a 2D array is the number of rows it has. The row index runs from 0 to length-1. Each row of a 2D array can have a different number of cells, so each row has its own length : uneven[0] refers to row 0 of the array, uneven[1] refers to row 1, and so on.

Can a list be 2 dimensional Python?

Python provides many ways to create 2-dimensional lists/arrays. However one must know the differences between these ways because they can create complications in code that can be very difficult to trace out.

How do I get the size of a list in Python?

Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.


3 Answers

length = sum([len(arr) for arr in mylist])

sum([len(arr) for arr in mylist[0:3]]) = 9
sum([len(arr) for arr in mylist[1:3]]) = 6
sum([len(arr) for arr in mylist[2:3]]) = 3

Sum the length of each list in mylist to get the length of all elements.
This will only work correctly if the list is 2D. If some elements of mylist are not lists, who knows what will happen...

Additionally, you could bind this to a function:

len2 = lambda l: sum([len(x) for x in l])
len2(mylist[0:3]) = 9
len2(mylist[1:3]) = 6
len2(mylist[2:3]) = 3
like image 181
Matt Bryant Avatar answered Sep 30 '22 06:09

Matt Bryant


You can use reduce to calculate the length of array indices like this, this can also handle the scenario when you pass in something like mylist[0:0]:

def myLen(myList):
    return reduce(lambda x, y:x+y, [len(x) for x in myList], 0)

myLen(mylist[0:3]) = 9
myLen(mylist[1:3]) = 6
myLen(mylist[0:1]) = 3
myLen(mylist[0:0]) = 0
like image 39
zs2020 Avatar answered Sep 30 '22 06:09

zs2020


You can flatten the list, then call len on it:

>>> mylist=[[1,2,3],[4,5,6],[7,8,9]]
>>> import collections
>>> def flatten(l):
...     for el in l:
...         if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
...             for sub in flatten(el):
...                 yield sub
...         else:
...             yield el
...
>>> len(list(flatten(mylist)))
9
>>> len(list(flatten(mylist[1:3])))
6
>>> len(list(flatten(mylist[0:1])))
3
like image 31
TerryA Avatar answered Sep 30 '22 04:09

TerryA