A tuple is a built-in data type in Python used to store a sequence of immutable Python objects. Tuples are defined by enclosing the elements in parentheses ()
and separating them with commas. Unlike lists, which are mutable, tuples cannot be modified after they are created.
Tuples are used in Python when you want to store a collection of items that should not change throughout the life of a program. This immutability can provide data integrity and ensure that the data is not accidentally modified, making tuples useful in scenarios where data should remain constant.
Tuples are commonly used:
- To return multiple values from a function: When a function needs to return multiple values, they can be packed into a tuple.
- As dictionary keys: Since tuples are immutable, they can be used as keys in a dictionary, unlike lists.
- To store related pieces of information: Tuples can be used to group different types of data together.
- For fixed collections: Storing fixed collections of items where immutability is required.
Feature | List | Tuple |
---|---|---|
Syntax | Defined using square brackets [] . |
Defined using parentheses () . |
Mutability | Mutable (can be modified). | Immutable (cannot be modified). |
Methods Available | Many built-in methods like append() , remove() , etc. |
Limited methods: count() , index() . |
Memory Consumption | Larger size due to extra features. | Smaller size, more memory efficient. |
Use Case | Suitable for collections that may change. | Suitable for fixed collections. |
- Immutable Data: Data that should not be changed once assigned.
- Multiple Return Values: Functions can return multiple values in a single tuple.
- Dictionary Keys: Tuples can be used as keys in dictionaries due to their immutability.
- Efficient Data Handling: Tuples have a smaller memory footprint compared to lists.
- Tuple Packing: When we pack values into a tuple.
- Tuple Unpacking: When we extract values back into variables.
# Tuple Packing
t = 12345, 54321, 'hello!'
print(t) # Output: (12345, 54321, 'hello!')
# Tuple Unpacking
a, b, c = t
print(a, b, c) # Output: 12345 54321 hello!
- Empty Tuple:
empty_tuple = ()
print(type(empty_tuple)) # Output: <class 'tuple'>
- Single Element Tuple:
single_tuple = ("Python",) # Note the comma
print(type(single_tuple)) # Output: <class 'tuple'>
- Multiple Elements:
multi_tuple = (1, 2, 3, "Python", True)
print(multi_tuple) # Output: (1, 2, 3, 'Python', True)
You can loop through all the values in a tuple using a for
loop:
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
# Output:
# 200
# 50
Tuples are immutable, meaning their elements cannot be modified after creation. Attempting to do so will raise an error:
dimensions = (200, 50)
dimensions[0] = 250 # Raises TypeError: 'tuple' object does not support item assignment
Tuples support indexing and slicing, just like lists:
tuple1 = (1, 2, 3, 4, 5, 6)
# Indexing
print(tuple1[0]) # Output: 1
print(tuple1[-1]) # Output: 6
# Slicing
print(tuple1[1:4]) # Output: (2, 3, 4)
print(tuple1[::2]) # Output: (1, 3, 5)
While you cannot delete an element from a tuple, you can delete an entire tuple using the del
keyword:
tuple1 = (1, 2, 3, 4, 5)
del tuple1
# print(tuple1) # Raises NameError: name 'tuple1' is not defined
Method | Description |
---|---|
count() |
Returns the number of times a specified value appears in the tuple. |
index() |
Returns the index of the first occurrence of a specified value in the tuple. |
tup = (1, 2, 2, 3, 4, 4, 4, 5)
# count()
print(tup.count(4)) # Output: 3
# index()
print(tup.index(2)) # Output: 1
- Constants: Use tuples for creating constants in your code.
- Function Arguments: Tuples can be used to represent fixed collections of items (like arguments) passed to functions.
- Returning Multiple Values from Functions: Functions can return multiple values as a tuple.
def get_user_info():
name = "John"
age = 30
return name, age
user_info = get_user_info()
print(user_info) # Output: ('John', 30)