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
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.
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.
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.
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With