0

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?

4
  • is there any chance that you can add some sample inputs and outputs that you're expecting for them? Commented Oct 21, 2017 at 19:39
  • Here my list: movies = ['Lord of the Rings', 'Star Trek', ['Captain Kirk', 'Spok', ['Big Bang', 'Other Movie' ]] ] Commented Oct 21, 2017 at 19:55
  • 1
    Add your code to show how far you have tried! Commented Oct 21, 2017 at 19:55
  • @ChristopherLeone , put the edits in your Question, not just commenting here. Commented Oct 21, 2017 at 19:56

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

You can use map:

final_length = sum(map(len, data))

1 Comment

wouldn't this be sum(map(len, data))?
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.