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.

Quintium
  • 358
  • 2
  • 11

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,745
  • 1
  • 28
  • 39
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
  • 3,369
  • 3
  • 11
  • 37
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
  • 3
  • 14