I'm a bit bewildered by the "in" keyword in python.
If I take a sample list of tuples:
data = [ (5, 1, 9.8385465), (10, 1, 8.2087544), (15, 1, 7.8788187), (20, 1, 7.5751283) ]
I can do two different "for - in" loops and get different results:
for G,W,V in data: print G,W,V
This prints each set of values on a line, e.g. 5, 1, 9.8385465
for i in data: print i
This prints the whole tuple, e.g. (5, 1, 9.8385465)
How does python "know" that by providing one variable I want to assign the tuple to a variable, and that by providing three variables I want to assign each value from the tuple to one of those variables?
The in keyword has two purposes: To check if a value is present in a list, tuple, range, string, etc. To iterate through a sequence in a for loop.
String Membership TestWe can test if a substring exists within a string or not, using the keyword in .
According to the for
compound statement documentation:
Each item in turn is assigned to the target list using the standard rules for assignments...
Those "standard rules" are in the assignment statement documentation, specifically:
Assignment of an object to a target list is recursively defined as follows.
If the target list is a single target: The object is assigned to that target.
If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.
So this different behaviour, depending on whether you assign to a single target or a list of targets, is baked right into Python's fundamentals, and applies wherever assignment is used.
This isn't really a feature of the in
keyword, but of the Python language. The same works with assignment.
x = (1, 2, 3) print(x) >>> (1, 2, 3) a, b, c = (1, 2, 3) print(a) >>> 1 print(b) >>> 2 print(c) >>> 3
So to answer your question, it's more that Python knows what to do with assignments when you either:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With