Table of Contents
ToggleA tuple in Python is a built-in data type that represents an ordered, immutable collection of items. Tuples are similar to lists but cannot be modified after creation. This guide covers everything you need to know about Python tuples, including accessing, updating, and manipulating tuple elements.
A tuple is a sequence of comma-separated items, enclosed in parentheses (). Tuples can contain items of different data types, such as integers, strings, floats, and even other tuples.
tup1 = ("Rohan", "Physics", 21, 69.75)
tup2 = (1, 2, 3, 4, 5)
tup3 = ("a", "b", "c", "d")
tup4 = (25.50, True, -55, 1+2j)
An empty tuple is written as (), and a tuple with a single item requires a trailing comma:
tup1 = (50,)
You can access tuple elements using their index. Python also supports slicing to access a range of elements.
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7)
print("tup1[0]:", tup1[0]) # Output: physics
print("tup2[1:5]:", tup2[1:5]) # Output: (2, 3, 4, 5)
Tuples are immutable, meaning you cannot modify their elements after creation. However, you can create a new tuple by combining existing tuples.
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Creating a new tuple by combining tup1 and tup2
tup3 = tup1 + tup2
print("New Tuple:", tup3) # Output: (12, 34.56, 'abc', 'xyz')
You cannot remove individual elements from a tuple, but you can delete an entire tuple using the del statement.
tup = ('physics', 'chemistry', 1997, 2000)
print("Original Tuple:", tup)
del tup
print("After deleting tup:")
# The following line will raise an error because the tuple no longer exists
# print(tup)
Tuples support various operations, such as concatenation, repetition, and membership checks.
| Python Expression | Results | Description |
|---|---|---|
(1, 2, 3) + (4, 5, 6) |
(1, 2, 3, 4, 5, 6) |
Concatenation |
('Hi!',) * 4 |
('Hi!', 'Hi!', 'Hi!', 'Hi!') |
Repetition |
3 in (1, 2, 3) |
True |
Membership |
Tuples support indexing and slicing, similar to strings. You can access elements using positive or negative indices.
L = ('spam', 'Spam', 'SPAM!')
print("L[2]:", L[2]) # Output: SPAM!
print("L[-2]:", L[-2]) # Output: Spam
print("L[1:]:", L[1:]) # Output: ('Spam', 'SPAM!')
If you write multiple objects separated by commas without any enclosing delimiters, Python treats them as a tuple.
print('abc', -4.24e93, 18+6.6j, 'xyz') # Output: abc -4.24e+93 (18+6.6j) xyz
x, y = 1, 2
print("Value of x, y:", x, y) # Output: Value of x, y: 1 2
Python provides several built-in functions to work with tuples.
| Sr.No. | Function | Description |
|---|---|---|
| 1 | len(tuple) |
Returns the length of the tuple. |
| 2 | max(tuple) |
Returns the item with the maximum value in the tuple. |
| 3 | min(tuple) |
Returns the item with the minimum value in the tuple. |
| 4 | tuple(seq) |
Converts a sequence (e.g., list) into a tuple. |
Enroll in our Python certification course at Vista Academy and become a certified expert to boost your career.
Enroll Now