I tried solving the problem by this
li = [ count=0 x for x in s if s[x]==' ' count+=1]
can we make a variable inside the list?
Asked
Active
Viewed 70 times
0
crish
- 1
-
No. This is not what list-comprehensions are for. They are, as their name suggests, for creating lists. Not counting... – Tomerikoo Feb 28 '22 at 17:11
-
You could use list comprehension to make a list *of* the spaces; the length of that list would be the count you are seeking. – Scott Hunter Feb 28 '22 at 17:12
-
1There is the built-in [`sum()`](https://docs.python.org/3/library/functions.html#sum) function which makes this quite easy: `sum(c == ' ' for c in s)`... – Tomerikoo Feb 28 '22 at 17:12
-
2Lists have a build in function that does this. you can simply call .count(' ') on your list. As @Tomerikoo indicates, same is true for a string – Stefan Feb 28 '22 at 17:12
-
@Stefan It sounds like the input is a string. But still, there exists [`str.count`](https://docs.python.org/3/library/stdtypes.html#str.count)... – Tomerikoo Feb 28 '22 at 17:14
-
@Tomerikoo You have back to back comments that read "Don't use a comprehension" and "Here is how to do it with a comprehension". Which is it? – JonSG Feb 28 '22 at 17:18
-
This is a duplicate of https://stackoverflow.com/questions/33864485/how-to-count-number-of-space-in-given-string-in-python not https://stackoverflow.com/questions/5753597/is-it-pythonic-to-use-list-comprehensions-for-just-side-effects The comprehension with side effects is a nuance of their attempted answer not the crux of their question. – JonSG Feb 28 '22 at 17:21
-
@JonSG Not sure I follow... Do you have examples of such comments? I didn't use a comprehension anyway. Inside the `sum` is a generator expression which is quite a different thing. I have added your link to the duplicate list as it is not really clear if the question is focusing on solving the problem or the list-comp aspect of it... – Tomerikoo Feb 28 '22 at 17:26