Liu yang
Liu yang

Reputation: 27

For loop with 2 variables after "in"

I am confused about the following statement

for sentence in snippet, phrase. 

Why there are two items behind the "in"

Full Code

def convert(snippet, phrase):
    class_names = [w.capitalize() for w in
                   random.sample(WORDS, snippet.count("%%%"))]
    other_names = random.sample(WORDS, snippet.count("***"))
    results = []
    param_names = []

    for i in range(0, snippet.count("@@@")):
        param_count = random.randint(1,3)
        param_names.append(', '.join(random.sample(WORDS, param_count)))

    for sentence in snippet, phrase:
        result = sentence[:]

        # fake class names
        for word in class_names:
            result = result.replace("%%%", word, 1)

        # fake other names
        for word in other_names:
            result = result.replace("***", word, 1)

        # fake parameter lists
        for word in param_names:
            result = result.replace("@@@", word, 1)

        results.append(result)

    return results

Upvotes: 2

Views: 75

Answers (3)

ForceBru
ForceBru

Reputation: 44838

This is another syntax (syntactic sugar) for tuples, which are an immutable data container. You could have written this like this:

for something in (1,2,3,4):

But in this case you can omit the parentheses, thus getting:

for something in 1,2,3,4:

That's also valid syntax.


Example to try:

for X in 1,2,3,4:
    print X 

Prints the following:

 1
 2
 3
 4

Upvotes: 3

davidawad
davidawad

Reputation: 1043

A for loop just goes through each item in an iterable collection. So range(5) returns the iterable collection of all items between 0 and 5. The for loop gives you access to that.

>>> for x in range(5):
...     print(x)
...
0
1
2
3
4
>>>

Upvotes: 0

Tom Karzes
Tom Karzes

Reputation: 24052

It's just a two-trip loop. On the first iteration, sentence is set to snippet. On the second iteration, sentence is set to phrase.

Here's a simple example:

>>> for x in "a", "b":
...     print(x)
...
a
b
>>>

Upvotes: 4

Related Questions