List membership check in Python 3 List membership check in Python 3 tkinter tkinter

List membership check in Python 3


You say you're new to Python, so I hope you don't mind a few tips.

There's really no reason to do [i for i in bits]. It's not wrong, but it's not really Pythonic. If you want a list, which is what this makes, you can just pass the string to the list function. If you want a copy of the string, you can use the slice operator.

bit_list = list(bits) # Convert to listbit_list = bits[:] # Shallow copy of a string

The good thing though, is you don't need a copy for this.


A really useful function of this is called any. You can check everything at once with it. Also, integers are easier to work with than strings. Converting the bits to integers means you don't need that list of strings.

bits = '011101'ill_bits = range(2, 9+1)if any(int(bit) in ill_bits for bit in bits):    print('Bad')else:    print('Good')

Basically it says, if any bit is in both bits and ill_bits the number is bad. Otherwise, it's good.


Your flow is a little off. You need to break after the first failure, and have the else block associated with the for instead of the if.


Just to provide an alternate solution, the shortest way to do this is with regular expressions:

import reif re.search('[2-9]', bits):    print('yes')else:    print('no')