0

Is it possible to write this logic in one line statement?

B = []
for book in books:
    if book not in B:
         B.append(book)

I have tried this but it's false:

B = [book if book not in B for book in books] 

Is there a way to reference the variable inside itself?

Wasi
  • 1,473
  • 3
  • 16
  • 32
pietà
  • 760
  • 1
  • 11
  • 37

1 Answers1

-5
B=[book for book in books if  not book in B] 

should do the trick

JMat
  • 752
  • 6
  • 14
  • I havetried this code but the books of B are duplicated .. – pietà Oct 06 '16 at 10:40
  • 2
    @pietà Because `B` is only being defined after this comprehension is done. This will actually fail with a `NameError: name 'B' is not defined`. If you still have a `B = []` defined previously you obviously circumvent that error… – deceze Oct 06 '16 at 10:43