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.