Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Built-In Data Types
  5. Tuple in Python

Tuple in Python

A tuple in Python is an ordered, immutable collection of items, enclosed in parentheses ( ). Like lists, tuples can store elements of different data types, but unlike lists, tuples cannot be changed after creation.

Thank you for reading this post, don't forget to subscribe!

Since tuples are immutable, you cannot directly change their values. To update a tuple, you must convert it to a list, make changes, and convert it back to a tuple.

Example:

t = (1, 2, 3)
temp = list(t)
temp[0] = 100
t = tuple(temp)
print(t)           # Output: (100, 2, 3)

You can access individual elements or slices of a tuple, just like with lists.

Example:

t = (10, 20, 30, 40)
print(t[1])        # Output: 20
print(t[1:3])      # Output: (20, 30)

Tuple unpacking allows you to assign the values of a tuple to individual variables in a single step.

Example:

a, b = (5, 10)
print(a)           # Output: 5
print(b)           # Output: 10

You can use a loop to iterate over the items in a tuple.

Example:

t = ('apple', 'banana', 'cherry')
for item in t:
    print(item)

Tuples can be joined (concatenated) using the + operator.

Example:

t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2
print(t3)          # Output: (1, 2, 3, 4)

How can we help?