Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python "know" what to do with the "in" keyword?

Tags:

python

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?

like image 623
Daniel B. Avatar asked Aug 03 '15 21:08

Daniel B.


People also ask

How does the in keyword in Python work?

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.

Does the in keyword work for strings Python?

String Membership TestWe can test if a substring exists within a string or not, using the keyword in .


2 Answers

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.

like image 62
jonrsharpe Avatar answered Oct 14 '22 22:10

jonrsharpe


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:

  • assign a tuple to a variable, or
  • assign a tuple to a number of variables equal to the number of items in the tuple
like image 24
BlivetWidget Avatar answered Oct 14 '22 22:10

BlivetWidget