Christopher Leone
Christopher Leone

Reputation: 11

Python len function on list with embedded sublists and strings

I have a list called movies with two sublists embedded it. Do the sublists have names too? I want to use len() BIF to measure all items in the list and sublists, how do I do that?

Upvotes: 0

Views: 116

Answers (4)

maor10
maor10

Reputation: 1794

If you want the total length of all the sublists, you can try:

sum([len(sub) for sub in container_list])

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71471

You can use map:

final_length = sum(map(len, data))

Upvotes: 0

Ashish Ranjan
Ashish Ranjan

Reputation: 5543

For the input you've provided, you can recursively find it's length like this :

def getLen(l):
    c = 0
    for e in l:
        if isinstance(e, list):
            c += getLen(e) # if the element is a list then recursively find it's length
        else:
            c += 1 # if not simply increase the count
    return c

OUTPUT :

>>> l = ['Lord of the Rings', 'Star Trek', ['Captain Kirk', 'Spok', ['Big Bang', 'Other Movie']]]
>>> getLen(l)
6

Upvotes: 1

Natesh bhat
Natesh bhat

Reputation: 13257

U can use the len() function by specifying the inner sublists

movies = [ [list1] , [list2] ] ; print(len(movies[0])); # prints length of 1st sublist print(len(movies[1])); #prints length of second sublist

Upvotes: 1

Related Questions