Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list/set comprehension with characters

Tags:

python

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?

like image 271
user2517984 Avatar asked Nov 25 '25 02:11

user2517984


1 Answers

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'}
like image 175
kalehmann Avatar answered Nov 27 '25 16:11

kalehmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!