Python tuples

Renesh Bedre    2 minute read

Python tuple is an immutable sequence and can be constructed using tuple() built-in, parentheses (), and comma-separated items without parentheses

Properties of tuples

  • Tuples can store heterogeneous (e.g., different data types) and homogenous data
  • tuple is an immutable, i.e., we can not change the values and order of values of tuple once initialized
  • As tuple is a sequence, it supports all sequence operations such as in, not in, max, count, etc.
  • Duplicate values allowed in the tuple

Tuples initialization

  • Tuples contain the comma-separated elements generally enclosed in parentheses.
x = ('python', 2, 3, 4, 5, 'julia')  # with parentheses
x = 'python', 2, 3, 4, 5, 'julia'  # without parentheses

# nested tuple
x = 'python', (2, 3, 4, 5)
x
('python', (2, 3, 4, 5))

Single element tuple

  • A comma must follow a single element tuple
x = ('julia',)  #

Access tuple elements

  • Tuples are heterogeneous sequence of elements and can be accessed by unpacking (see Tuple assignment) or by indexing
x = (1, 2, 3, 4, 5, 'a')  
x[2]
# output
3

# slice tuple
x[2:5]
(3, 4, 5)

Tuple assignment and unpacking

  • Tuples assignment feature allow tuple to unpack elements and assign to the variables on left side
x, y, z = ('python', 'julia', 'R')  
x
'python'

y
'julia'

Tuples are immutable

  • Unlike the list, tuples are immutable. It means it is not possible to change the values of tuples once it is created.
# lets try to add 'd' value in tuple
x[2] = 'd' 
TypeError: 'tuple' object does not support item assignment

Merge tuples

  • Merge/join multiple tuples
x = ('python', 'julia', 'R')  
y = (1, 2, 3)
# merge tuples
x+y
('python', 'julia', 'R', 1, 2, 3)

Insert elements in tuples

  • Even though tuples are immutable, you can insert an element in a tuple by creating a new tuple
x = ('python', 'julia', 'R')  
# insert element in a tuple
y = x[:1]+('go',)+x[1:]
y
('python', 'go', 'julia', 'R')

Interconversion of tuple and list

# tuple to list
x = ('python', 'julia', 'R')  
list(x)
['python', 'julia', 'R']

# list to tuple
x = ['python', 'julia', 'R']
tuple(x)
('python', 'julia', 'R')

Enhance your skills with courses on Python and pandas

References

This work is licensed under a Creative Commons Attribution 4.0 International License

Some of the links on this page may be affiliate links, which means we may get an affiliate commission on a valid purchase. The retailer will pay the commission at no additional cost to you.

Tags:

Updated: