Tuples are immutable sequences of values. The values can be heterogeneous. The values in a tuple are indexed by integers.

Tuple construction:

  • () for empty tuple
  • Single value in a tuple requires a trailing comma: 1,
  • Comma separated values: 1,2,3
  • using tuple() function

Examples:

Empty tuple.

t0=() 

Single value in a tuple(singleton). Notice the trailing comma.

t1='a',
print(t1)
('a',) 

Comma separated values.

t2=1,2,3
print(t2)
(1, 2, 3)

Using the tuple() function. Note that it accepts only one argument.

t3=tuple()
print(t3)
()

#trailing comma not required
t4=tuple('a')
print(t4)
('a',)

t5=tuple('abcd')
print(t5)
('a', 'b', 'c', 'd')

t6=tuple(1234)
TypeError: 'int' object is not iterable

The tuple() function does not accept integers as they are not iterable. To understand what iterables are, refer to the official docs.

Tuples are immutable:

t2[0]=456
TypeError: 'tuple' object does not support item assignment

Tuple packing is the process of packing values into a tuple.

t7=123,'abc',345
print(t7)
(123, 'abc', 345) 

Tuple unpacking is the opposite.

var1,var2,var3=t7
print(var1)
123
print(var2)
abc
print(var3) 
345

The source code for today’s plog is available here.