Tuple
A tuple is a versatile data structure in Python that is used to group multiple values into a single object. Below, I’ll explain its properties, how it differs from lists, and how it applies and student data requirements.
- Tuples store multiple values, which can be of any data type (integers, strings, floats, booleans, complex numbers, or even other tuples or lists).
- Elements are enclosed in parentheses () and separated by commas.
- Example: var = (10, 20, 10, 34, 56, 20) stores integers with duplicates.
- Tuples can be empty: var1 = () or var1 = tuple().
- Single-element tuple: Requires a trailing comma (e.g., var2 = (10,) is a tuple, but var2 = (10) is an integer).
- Without parentheses: var5 = 10, "Travis", 56.78 automatically creates a tuple (called tuple packing).
# Create a tuple with values
var = (1,2,3,4)
print(var,type(var))
# Create an empty tuple
var1 = ()
print(var(),type(var))
var1 = tuple()
print(var1,type(var1))
# single- element tuple
var2 = (10,)
print(var2,type(var2))
var2 = (10)
print(var2,type(var2))
# # tuple without parentheses
var5 = 1, True, "hello"
print(var5)
# Create a tuple with duplicate values
var = (1,1,2,2,3,3,4,4)
print(var,type(var))
- Indexing: Access elements using zero-based indices (e.g., t1[0] returns 10).
- Negative Indexing: Access elements from the end (e.g., t1[-1] returns the last element).
- Slicing: Extract a subset of elements (e.g., t1[1:3] returns (20, 10)).
# Define the student data as a tuple
student = (10, "Rossum", (15, 20, 30), (60, 65, 55), "OUCET")
# Print the entire tuple
print(student) # Output: (10, 'Rossum', (15, 20, 30), (60, 65, 55), 'OUCET')
# Access individual elements
print(student[0]) # Output: 10 (student number)
print(student[1]) # Output: Rossum (name)
print(student[2]) # Output: (15, 20, 30) (internal marks)
print(student[2][0]) # Output: 15 (internal mark for sub1)
print(student[3]) # Output: (60, 65, 55) (external marks)
print(student[3][1]) # Output: 65 (external mark for sub2)
print(student[4]) # Output: OUCET (college name)
# Slicing example
print(student[2:4]) # Output: ((15, 20, 30), (60, 65, 55)) (internal and external marks)
# Length of the tuple
print(len(student)) # Output: 5
- Immutability: Once created, a tuple’s elements cannot be changed. You cannot append, remove, or modify elements. However, if a tuple contains mutable objects (e.g., a list), the contents of those objects can be modified.
- Ordered & heterogeneous: Tuple() is ordered, and we can store heterogeneous data
- Both tuples and lists store multiple values, support indexing/slicing, and maintain insertion order.
- Lists are mutable (lst[0] = 100 is valid), while tuples are immutable (t1[0] = 100 raises a TypeError).
- Tuples are slightly faster than lists due to immutability, making them suitable for fixed data.
- Use tuples for data that shouldn’t change (e.g., coordinates, database records).
- Use lists for data that may need modification (e.g., a dynamic collection).