wontleave
wontleave

Reputation: 177

Logic of comparision using "in" for tuples

I am having trouble in understanding the logic of using "in" for tuples

For instance,

t = (0, 2, 2.0, 5.0)
(0) in t gives True #or any single element of t
(0, 2) in t gives False
(0, 2, 2.0) in t gives False

t = [(0, 2, 2.0, 5.0),(0, 1, 0.0, -1.5)]
(0) in t gives False

Please kindly enlighten me. Thank you!

Upvotes: 1

Views: 48

Answers (2)

Siddhant Kaushal
Siddhant Kaushal

Reputation: 407

As when your search (0) in tuple, it is just searching one single element 0 which is an integer in the tuple.. So it returns True. When you do a search for (0,2), you are actually searching a tuple inside the tuple which in not present in t, so it returns False in that case. :)

In [7]: t = (0, 2, 2.0, 5.0)                                                                                                                                                         

In [8]: (0,2) in t                                                                                                                                                                   
Out[8]: False

In [9]: t = (0, 2, 2.0, 5.0,(0,2))                                                                                                                                                   

In [10]: (0,2) in t                                                                                                                                                                  
Out[10]: True

Upvotes: 1

Akavall
Akavall

Reputation: 86286

Your tuple (0, 2, 2.0, 5.0) does contain (0) because it is just an int, 0.

It does not contain (0, 2) because no such tuple is present inside (0, 2, 2.0, 5.0).

Here is an example of a tuple that does contain (0, 2):

In [3]: (0,2) in ((0,2),)
Out[3]: True

Upvotes: 2

Related Questions