0

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)))
martineau
  • 119,623
  • 25
  • 170
  • 301
thanos
  • 1
  • 2
    What exactly do you need explained? Do you not understand what `(a,)` means (see [here](https://stackoverflow.com/questions/3750632/why-does-adding-a-trailing-comma-after-a-variable-name-make-it-a-tuple) for an explanation)? Or you're wondering why it's being used in that way? Regardless, when you don't understand code, I **HIGHLY** recommend stepping through the code line-by-line in a debugger. PyCharm is free and has a great debugger, [here](https://www.jetbrains.com/help/pycharm/debugging-your-first-python-application.html) is some info about it. – Random Davis Dec 09 '21 at 23:42

1 Answers1

1

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.

AbbeGijly
  • 1,191
  • 1
  • 4
  • 5