This question already has an answer here:
have a look at the following piece of code:
class a:
s = 'python'
b = ['p', 'y']
c = [x for x in s]
the output:
>>> a.c
['p', 'y', 't', 'h', 'o', 'n']
but when i try to limit the list with if:
class a:
s = 'python'
b = ['p', 'y']
c = [x for x in s if x in b]
Shows the following exception:
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
class a:
File "<pyshell#22>", line 4, in a
c = [x for x in s if x in b]
File "<pyshell#22>", line 4, in <listcomp>
c = [x for x in s if x in b]
NameError: global name 'b' is not defined
If a make global b
it works, why this is happening?
This isn't so much about the variable scope in list comprehensions as about the way classes work. In Python 3 (but not in Python 2!), list comprehensions don't affect the scope around them:
However, when you do that in a class, it won't look for
b
among the class attributes the way it would in the local scope of a module or function. To do what you are trying to do, use the@property
decorator:Also, remember that strings are iterable too (they're just lists of their component characters), so no need to explicitly make
b
a list.