Python counts the number of lines in a list of variable types if loop is not possible
would like to count the number of lines in a list of variable types, if possible:
l = [1,2,3,'a','b'] c = l.count(str) print (c)
output:
0
expected output:
2
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.
My solution is probably a little tedious, but here's my attempt
l = [1,2,3,'a','b']
Concatenate all list items on one line
ll = ''.join(map(str,l))
Then do the count on it
letters = sum(c.isalpha() for c in ll)