Developer
Developer

Reputation: 1022

Python for in loop to generate dictionary

I came across this snippet of code, I understand it's a Cartesian product but if someone can break up this line for me [s+t for s in a for t in b] from the following code along with docs link for this kind of syntax.

Apparently this for in syntax with s+t??? is foreign for me and I'm new to python as well. Appreciate docs link so I can understand more about this syntax since there are other variations of for in loops that I'm trying to understand.

rows = 'ABCDEFGHI'
cols = '123456789'

def cross(a, b):
    return [s+t for s in a for t in b]

def main():
    print(cross(rows, cols))

if __name__ == "__main__": main()

Upvotes: 0

Views: 133

Answers (2)

Julian Chan
Julian Chan

Reputation: 466

It can be broken down into:

lst = []
for s in A:
    for t in b:
        lst.append(s+t)
return lst

Hope this helps!

Upvotes: 1

perigon
perigon

Reputation: 2095

This is a shorthand syntax known as a list comprehension. See section 5.1.4 of the docs: https://docs.python.org/2/tutorial/datastructures.html

The line is exactly equivalent to this:

lst = []
for s in a:
    for t in b:
        lst.append(s+t)
return lst

It just finds the sums of every pair of an element in a and an element in b.

Upvotes: 3

Related Questions