Python counts the number of lines in a list of variable types if loop is not possible
2 answers
Since Guido is not a big fan of map
and filter
, I'll give an answer that avoids them:
len([v for v in k if isinstance(v, str)])
Only those that are strings are counted here. This is wasteful because it builds the entire list in memory. There is no way to get the full length of the generator, but there are hacks.
sum(isinstance(v, str) for v in k)
This works because the sum of booleans is the number of values True
, hence the number of lines. Thank vaultah for the clarification.
+2
source to share