Short hands of loops and conditions

#shorthand.py
result = []
for x in [1,2,3]:
    for y in [3,1,4]:
        if x != y:
            result.append((x, y))
print(result)

result=[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
print(result)

Output
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Comments

Popular posts from this blog

Converting Excel File to JSON File using xlrd module

Using Oracle with Python

Using time module