Reputation: 69
I have a list which contains the numbers (lijstkleur) 1,4,6,7. I also have a range from 0 till 8. Now i have te following code:
for x in range(0, len(L), 1):
if x in lijstkleur == True:
self.label = Label(self.frame, text=string[x], fg="yellow", bg="red")
self.label.pack(side=LEFT)
else:
self.label = Label(self.frame, text=string[x], fg="white", bg="red")
self.label.pack(side=LEFT)
but all the numbers become white, what is wrong with this if statement
Upvotes: 1
Views: 1269
Reputation: 1124818
No need to use == True
:
if x in lijstkleur:
The expression x in lijstkleur==True
is interpreted as (x in lijstkleur) and (lijstkleur == True)
; a list is never equal to boolean True
and thus you end up testing something and False
, guaranteed to be False
instead. This is called comparison chaining, making expressions like 10 < a < 20
possible.
You can simplify your range()
call to just len(L)
:
for x in range(len(L)):
and there is no need to repeat the .pack()
call:
if x in lijstkleur:
self.label=Label(self.frame,text=string[x],fg="yellow",bg="red")
else:
self.label=Label(self.frame,text=string[x],fg="white",bg="red")
self.label.pack(side=LEFT)
Upvotes: 5
Reputation: 17188
Your conditional isn't evaluating the way you think it is. It's doing this:
if (x in lijstkleur) and (lijstkleur==True):
The result of lijstkleur==True
is always False
, since a list is never equal to a boolean, so the conditional always returns False
. What you want is this:
if x in lijstkleur:
Upvotes: 1