I was trying to get a set of all characters from a list of strings using two level comprehension:
words = ['foo','bar']
s = {c for c in w for w in l}
But got the following error:
NameError: name 'w' is not defined
I wonder if it is because w is not a list object. If so is there any other way we can quickly get character set from a list of strings?
A comprehension in python ist evaluated from the left to right. That means, your outer loop has to come first. Therefore you need to swap the loops:
words = ['foo','bar']
s = {c for w in words for c in w}
Output:
{'a', 'b', 'r', 'f', 'o'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With