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?
-
is there any chance that you can add some sample inputs and outputs that you're expecting for them?Ashish Ranjan– Ashish Ranjan2017-10-21 19:39:59 +00:00Commented Oct 21, 2017 at 19:39
-
Here my list: movies = ['Lord of the Rings', 'Star Trek', ['Captain Kirk', 'Spok', ['Big Bang', 'Other Movie' ]] ]Christopher Leone– Christopher Leone2017-10-21 19:55:07 +00:00Commented Oct 21, 2017 at 19:55
-
1Add your code to show how far you have tried!Xenolion– Xenolion2017-10-21 19:55:23 +00:00Commented Oct 21, 2017 at 19:55
-
@ChristopherLeone , put the edits in your Question, not just commenting here.Kaushik NP– Kaushik NP2017-10-21 19:56:41 +00:00Commented Oct 21, 2017 at 19:56
Add a comment
|
4 Answers
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
You can use map:
final_length = sum(map(len, data))
1 Comment
TemporalWolf
wouldn't this be
sum(map(len, data))?