0

I am building my class and starting by defining 3 class attributes like this:

> class Test:
    first_list= [1,2,3,4,5]
    second_list = [1,2]
    third_list = [
        ex for ex in first_list if ex not in second_list
    ]

I am using the class variable 'first_list' and the class variable second_list to define a new class variable 'third_list' in a list comprehension

I get a NameError name 'second_list' is not defined

Cant understand why

If I define my third_list as :

third_list = first_list + second_list

all works fine

it seems I cannot use 2 class variables inside a comprehension ! but one only works:

third_list = [ex for ex in first_list if ex not in [1,2]]
userJ
  • 21
  • 3
  • You can do it in init if it's fits for your case: `def __init__(self): self.third_list = [ex for ex in self.first_list if ex not in self.second_list]` – frost-nzcr4 Mar 23 '20 at 09:11
  • 1
    The long and the short of it is that it is best to avoid list-comprehensions in class definition scopes. A list comprehension is essentially implemented as a function, and as you probably know already class scopes do not create enclosing scopes (which is why you can't access `first_list` inside a method, you need `Test.first_list`). this case, the *leftmost* iterable in a possibly chained `for x in foo for y in bar ...` part of a list comprehension is special-cased, because it is essentially passed as an argument to a function which executes your list comprehension. – juanpa.arrivillaga Mar 23 '20 at 09:56

0 Answers0