Use of Lists, Tupples, or Sets in IF statement.

Rustom Mody rustompmody at gmail.com
Tue Mar 15 02:30:01 EDT 2016


On Tuesday, March 15, 2016 at 5:56:54 AM UTC+5:30, jj0ge... at gmail.com wrote:
> In Python is it possible to comparison-equate a variable to a List, Tupple, or Set and have it return True if the contents of the variable matches an element in the List, Tupple, or Set.
> 
> E.g.
> 
> x = "apple"
> 
> x-list = ["apple", "banana", "peach"]
> 
> If x == x-list:
>     print('Comparison is True')
> else:
>     print('Comparison is False')

Others have answered some parts
>>> if x in x_list:
...     print("That is a fruit.")
... else:
...     print("That is not a fruit.")
... 

However one can distribute the print out of the if; Thus

print ("This is a fruit" if x in x_list else "This is not a fruit")

Which can be further distributed:

print "This is %s a fruit" % ("" if x in x_list else "not")


And once you do that you may see that mostly you dont want the print at all.

>>> "This is %s a fruit" % ("" if x in x_list else "not")

See expression oriented thinking here:
http://blog.languager.org/2012/10/functional-programming-lost-booty.html



More information about the Python-list mailing list