1

When I declare a as ((5, 3)), I want a[0] to be equal to (5, 3). However, Python simpifies the expression to (5, 3).

Why are tuples simplified like that and do I have to use lists to express the same thing? ((5, 3), (3, 8)) works just fine.

R. B.
  • 328
  • 1
  • 9

3 Answers3

4

Tuples with a single element must be declared with the syntax (x,). Otherwise, parentheses are interpreted as a means of clarifying computations (or changing priorities with respect to operations).

Anthony Labarre
  • 2,605
  • 1
  • 26
  • 38
2

You can add a blank value as a second item, so that Python doesn't simplify the tuple:

# Python Terminal
>>> ((5, 3))
(5, 3)
>>> ((5, 3),)
((5, 3),)
>>> ((5, 3),)[0]
(5, 3)
Xiddoc
  • 1,810
  • 3
  • 6
  • 23
1

If you declare a=((1, 2), ) this will give you a tuple where the first element is another tuple.

a = ((1,2), )
print(a[0])
# Output: (1, 2)
Artin Zareie
  • 160
  • 2
  • 13