In Python, the tuple() constructor is a built-in function that is used to create tuple objects. A tuple is similar to a list, but it is immutable (elements can not be changed after creating tuples). You can use the tuple() constructor to create an empty tuple, or convert an iterable (such as a list, string, or range) into a tuple.
Example:
# Example
t1 = tuple() # creates an empty tuple
t2 = tuple([1, 2, 3]) # converts a list into a tuple
t3 = tuple("Python") # converts a string into a tuple
print(type(t1), t1)
print(type(t2), t2)
print(type(t3), t3)
Output
<class 'tuple'> ()
<class 'tuple'> (1, 2, 3)
<class 'tuple'> ('P', 'y', 't', 'h', 'o', 'n')
Syntax of tuple()
tuple([iterable])
- iterable: This is an optional argument. If provided,
tuple()will convert the iterable (like a list, string, or range) into a tuple. - If no iterable is passed, it creates an empty tuple
().
Use of Tuple() Constructor
The tuple() constructor is mainly used to:
- Create an empty tuple.
- Convert other iterables, such as lists, strings, ranges, etc., into tuples.
Let's see some examples:
Convert a Range to a Tuple
The range() function creates a range object, and we can use tuple() to convert it into a tuple.
t = tuple(range(5))
print(t)
Output
(0, 1, 2, 3, 4)
Convert a List Comprehension to a Tuple
Here, we are converting a tuple from a generator expression, which squares each number in the range from 0 to 4.
t = tuple(x * x for x in range(5))
print(t)
Output
(0, 1, 4, 9, 16)
Creating Nested Tuples
You can also create nested tuples using the tuple() constructor. Here's an example where we create a tuple of tuples, forming a 2D structure.
mat = tuple([tuple(range(3)) for _ in range(3)])
print(mat)
Output
((0, 1, 2), (0, 1, 2), (0, 1, 2))
Shallow Copy of a Tuple Using tuple()
Since tuples are immutable, you cannot change their elements once created. However, you can create a shallow copy of a tuple by using the tuple() constructor. This might be useful when you want to duplicate a tuple object.
t1 = ([1, 2], [3, 4])
t2 = tuple(t1)
t2[0][0] = 10 # Modifies the list inside tuple
print(t1) # Output: ([10, 2], [3, 4])
Output
([10, 2], [3, 4])
Explanation: In this case, although b and b1 are separate tuples, the lists inside them are not copied, so changes to the lists inside b1 will reflect in b.