Hailey Monette
Hailey Monette

Reputation: 97

How to find length of a multi-dimensional list?

How do you find the length of a multi-dimensional list?

I've come up with a way myself, but is this the only way to find the number of values in a multi-dimensional list?

multilist = [['1', '2', 'Ham', '4'], ['5', 'ABCD', 'Foo'], ['Bar', 'Lu', 'Shou']]
counter = 0
for minilist in multilist:
    for value in minilist:
        counter += 1

print(counter)

I'm pretty sure there is a much simpler way to find the length of a multi-dimensional list, but len(list) does not work, as it only gives the number of lists inside. Is there a more efficient method than this?

Upvotes: 7

Views: 16129

Answers (4)

GlacierSG
GlacierSG

Reputation: 469

If you want the number of items in any n-dimensional list then you need to use a recursive function like this:

def List_Amount(List):
    return _List_Amount(List)
def _List_Amount(List):
    counter = 0
    if isinstance(List, list):
        for l in List:
            c = _List_Amount(l)
            counter+=c
        return counter
    else:
        return 1

This will return the number of items in the list no matter the shape or size of your list

Upvotes: 1

Anti Earth
Anti Earth

Reputation: 4811

Another alternative (it's this or watch missed math lectures...)

def getLength(element):
    if isinstance(element, list):
        return sum([getLength(i) for i in element])
    return 1

This allows different degrees of 'multi-dimensionality' (if that were a word) to coexist.

eg:

>>> getLength([[1,2],3,4])
4

Or, to allow different collection types

def getLength(element):
    try:
        element.__iter__
        return sum([getLength(i) for i in element])
    except:
        return 1

eg:

>>> getLength([ 1, 2, (1,3,4), {4:3} ])
6
>>> getLength(["cat","dog"])
2

(Noting that although strings are iterable, they do not have the __iter__ method-wrapper and so will not cause any issues...)

Upvotes: 0

jamylak
jamylak

Reputation: 133554

Alternative to @mgilson's solution

sum(map(len, multilist))

Upvotes: 5

mgilson
mgilson

Reputation: 309919

How about:

sum(len(x) for x in multilist)

Upvotes: 12

Related Questions