Using the in Operator on Tuples, Sets, and Dictionaries

As with lists, the in operator can be applied to tuples and sets to check whether an item is a member of the collection:

 >>>​​ ​​odds​​ ​​=​​ ​​set([1,​​ ​​3,​​ ​​5,​​ ​​7,​​ ​​9])
 >>>​​ ​​9​​ ​​in​​ ​​odds
 True
 >>>​​ ​​8​​ ​​in​​ ​​odds
 False
 >>>​​ ​​'9'​​ ​​in​​ ​​odds
 False
 >>>​​ ​​evens​​ ​​=​​ ​​(0,​​ ​​2,​​ ​​4,​​ ​​6,​​ ​​8)
 >>>​​ ​​4​​ ​​in​​ ​​evens
 True
 >>>​​ ​​11​​ ​​in​​ ​​evens
 False

When used on a dictionary, in checks whether a value is a key in the dictionary:

 >>>​​ ​​bird_to_observations​​ ​​=​​ ​​{​​'canada goose'​​:​​ ​​183,​​ ​​'long-tailed jaeger'​​:​​ ​​71,
 ...​​ ​​'snow goose'​​:​​ ​​63,​​ ​​'northern fulmar'​​:​​ ​​1}
 >>>​​ ​​'snow goose'​​ ​​in​​ ​​bird_to_observations
 True
 >>>​​ ​​183​​ ​​in​​ ​​bird_to_observations
 False

Notice that the values in the dictionary are ignored; the in operator only looks at the keys.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.89.18