Python tuple()
Function
The tuple() function in Python is used to create an immutable ordered collection of elements called a tuple. Tuples are similar to lists, but they cannot be changed after creation.
Syntax
tuple(iterable)
Parameters:
iterable
– (Optional) Any iterable like a list, string, set, or dictionary.
Returns:
- A new tuple containing elements from the given iterable.
Example 1: Convert a List to Tuple
my_list = [1, 2, 3]
result = tuple(my_list)
print(result)
(1, 2, 3)
Example 2: Convert a String to Tuple
text = "abc"
result = tuple(text)
print(result)
('a', 'b', 'c')
Example 3: Using tuple()
with a Dictionary
my_dict = {'a': 1, 'b': 2}
result = tuple(my_dict)
print(result)
('a', 'b')
Note: Only the keys are included in the resulting tuple.
Example 4: Create an Empty Tuple
empty = tuple()
print(empty)
()
Why Use Tuples?
- Immutability: Tuples can’t be modified, making them useful for fixed data.
- Performance: Faster than lists for read-only data.
- Hashable: Tuples can be used as dictionary keys or set elements (if they only contain hashable items).
Common Mistakes
- Writing
tuple = ()
and then usingtuple()
will cause an error (do not overwrite built-ins). - Confusing parentheses
()
with tuple creation – remember,()
alone is empty tuple,(5)
is just a number, use(5,)
to create a one-element tuple.
Interview Tip
In interviews, tuples are often used when returning multiple values from functions, or for storing coordinates, RGB values, etc.
Summary
tuple()
converts an iterable into a tuple.- Tuples are immutable – you can't change them after creation.
- Empty tuple:
tuple()
; one-item tuple:(item,)
.
Practice Problem
Convert the following list into a tuple, and then try to change one value. What happens?
numbers = [10, 20, 30]
t = tuple(numbers)
print(t)
# Try this:
# t[0] = 99 # What error do you get?