Search code examples
pythonfor-in-loop

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()

Solution

  • 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.