
Python cartesian product: Advanced example of list comprehension
The code shows how to make a cartesian product in Python. This is an advanced example of Python list comprehension.
u = ['A', 'B']
v = ['a', 'b', 'c']
w = [x + y for x in u for y in v]
print(w)
# ['Aa', 'Ab', 'Ac', 'Ba', 'Bb', 'Bc']
Cartesian product is so important in math. If not using Python list comprehension, you may write like this.
u = ['A', 'B']
v = ['a', 'b', 'c']
w = []
for i in u:
for j in v:
w.append(i + j)
Of course, it's OK. Which style is better depends on the programmar's or team's preference.
Comments
Powered by Markdown