Reputation: 1
Could anybody please help me understand the below statement in the code below it?
cartesian_powers = [ i+(a,) for i in cartesian_powers for a in A]
Specifically the role of i+(a,)
?
Please explain the answer as much as possible.
Code:
A = {1, 2, 3}
k = 2
# Initialize every element as a tuple
cartesian_powers = [(a,) for a in A]
for j in range(k-1):
cartesian_powers = [ i+(a,) for i in cartesian_powers for a in A]
print("Tuples in {}^{}: {}".format(A,k,set(cartesian_powers)))
print("Size = {}".format(len(cartesian_powers)))
Upvotes: 0
Views: 44
Reputation: 1211
Note that cartesian_powers
is initialized using the same (a,)
syntax, indicating the elements are tuples, each containing a single integer.
In [ i+(a,) for i in cartesian_powers for a in A]
, i
and (a,)
are each tuples, so the addition i+(a,)
*concatenates the tuples, returning a two-integer tuple.
I think the addition syntax i+(a,)
to represent tuple concatenation is causing the confusion.
Upvotes: 1