Looking for a value in a list - Python
Archive - Originally posted on "The Horse's Mouth" - 2008-09-08 17:04:45 - Graham EllisIn any scripting language, avoiding loops makes for easier to write and faster to run code. One example is Pythons if .. in construct, where you can avoid a loop to test whether a value matches any member of a list or tuple.
Example:
stuff = ["red","green","blue"]
if "green" in stuff: print ("On the grassy field")
if "brown" in stuff: print ("On the muddy soccer pitch")
No need for a loop - just one test and we find that we're in the green stuff and not the brown stuff!
Dorothy:~ grahamellis$ python brst
On the grassy field
Dorothy:~ grahamellis$