Use of Lists, Tupples, or Sets in IF statement.
Steven D'Aprano
steve at pearwood.info
Mon Mar 14 22:10:03 EDT 2016
On Tue, 15 Mar 2016 11:26 am, jj0gen0info 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"]
You don't want to compare with "apple" *equals* the list, you want to
compare whether "apple" is contained *in* the list.
if x in x_list:
print('Comparison is True')
If the list is very large, this might be slow. You should use a set instead
of a list. In Python 3, change the square brackets to curly ones:
{"apple", "banana", "peach"}
In Python 2, you have to pass the list to the set() function:
set(["apple", "banana", "peach"])
For just three items, there's little difference in performance, but if you
find yourself with (say) three hundred items, the set version will be much
faster.
--
Steven
More information about the Python-list
mailing list