Python tuple(): Create an Immutable Ordered Collection

The tuple() function creates an ordered, immutable sequence of elements. It’s useful for storing multiple values, ensuring data consistency, and improving performance over lists.

Example

numbers = tuple([1, 2, 3, 4])
print(numbers)

Output:

(1, 2, 3, 4)

Converts a list into a tuple.

Syntax

tuple(iterable)
  • iterable (optional) → A sequence (list, string, range) to convert into a tuple.
  • Returns → An immutable tuple.

1. Creating a Tuple

t = (10, 20, 30)
print(t)  
# Output: (10, 20, 30)

Tuples store multiple items in an ordered manner.

2. Creating a Tuple from a String

word = "hello"
t = tuple(word)
print(t)  
# Output: ('h', 'e', 'l', 'l', 'o')

Breaks a string into characters.

3. Single-Element Tuple (Must Include a Comma)

single = (5,)  
print(single)  
# Output: (5,)

Using (5) creates an integer, but (5,) creates a tuple.

4. Unpacking a Tuple

person = ("Alice", 25, "Engineer")
name, age, job = person

print(name)  # Output: Alice
print(age)   # Output: 25
print(job)   # Output: Engineer

Assigns each element to a variable.

5. Tuple vs List (Key Differences)

Feature Tuple ( ) List [ ]
Mutable? ❌ No (Immutable) ✅ Yes (Mutable)
Performance ✅ Faster ❌ Slower

By using tuple(), you can store immutable data efficiently, ensure data consistency, and improve performance. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top