1

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

Marcin Pietraszek
3,2221 gold badge21 silver badges31 bronze badges
asked Apr 3, 2013 at 16:10

2 Answers 2

5

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)
answered Apr 3, 2013 at 16:11
1
  • And no need for for x in range(0,len(L),1) when for x in range(len(L)) will do. Or for x, s in zip(L, string). And self.label.pack(side=LEFT) can be hoisted ... There's a lot here. Commented Apr 3, 2013 at 16:15
1

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:
answered Apr 3, 2013 at 16:14
3
  • lijstkleur==True is True.. or False.. neither of them are iterable. Why don't you get any error message? Commented Apr 3, 2013 at 16:15
  • @KarolyHorvath Whoops; skipped a piece. Fixed. Commented Apr 3, 2013 at 16:18
  • Ahh.. I forgot that operators can be on both side. Thx! Commented Apr 3, 2013 at 16:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.