1

This was a code I stumbled upon to:

tuple1 = 10, 20
tuple2 = (10, 20)

print(type(tuple1))
print(type(tuple2))

bdmwx
  • 13
  • 4
  • 5
    Because ``,`` defines a tuple. – MisterMiyagi Apr 20 '21 at 09:27
  • 1
    This will do it too: `t = 10,` – S3DEV Apr 20 '21 at 09:28
  • 1
    If you assign multiple values to a variable like that then they are stored in a tuple. Similarly, if you return multiple values separated with a comma then they are returned in a tuple. – Kemp Apr 20 '21 at 09:28
  • 1
    Does this answer your question? [Python tuple … is not a tuple? What does the comma do?](https://stackoverflow.com/questions/41067409/python-tuple-is-not-a-tuple-what-does-the-comma-do) – MisterMiyagi Apr 20 '21 at 09:28
  • 1
    The comma defines a tuple, not the parentheses. – 9769953 Apr 20 '21 at 09:30
  • 1
    This question was wrongly closed as a duplicate. The supposed "duplicate" specifically concerns expressions with trailing commas. This question is asking about the general syntax for tuples with/without parentheses. To a new programmer it would not be obvious that these are special cases of the same syntax. – augurar Apr 20 '21 at 09:34

2 Answers2

1

That's how the syntax for tuples works. The parentheses are optional when creating a tuple.

... on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression).

augurar
  • 12,081
  • 6
  • 50
  • 65
1

When you use comma-separated expressions on the right-hand side of an assignment, this is called “tuple packing”. It creates a tuple; parentheses are not required for this:

tuple1 = 10, 20

Similarly, if you give comma-separated names on the left-hand side of an assignment, “tuple unpacking” is performed:

int1, int2 = tuple1

This is how multiple assignment works – It’s actually tuple packing combined with tuple unpacking:

int1, int2 = 10, 20

You can use this to swap the values of two variables without having to use a temporary variable:

int1, int2 = int2, int1
inof
  • 465
  • 3
  • 7