Table of Content
Tuples
Python tuples are immutable ordered collections of elements, defined using parentheses (). They're used to store fixed data sets and are faster and memory-efficient compared to lists.
Remember the last topic 'List', those are mutable which means we can modify it as per our needs. For details click here and have a look at it once again
Creation and Initialization:
# Creating a tuple
coordinates = (3, 4)
Accessing Elements:
Accessing elements of our tuple 'coordinates'.
coordinates = (3, 4)
print(coordinates[0])
print(coordinates[1])
Output:
3
4
Length of Tuple:
Yes we can obviously check the length of our tuple even if it's immutable in nature.
print(len(coordinates))
Output:
2
Immutable Nature:
As mentioned earlier, tuples are immutable.
# Attempting to modify a tuple (will result in an error)
# coordinates[0] = 5 # This line will raise a TypeError
In conclusion, tuples in Python are immutable ordered collections of elements, defined using parentheses `()`. They provide a fixed data structure for storing related items together. Although tuples lack the mutability of lists, their immutability offers benefits in terms of performance and data integrity. Tuples are commonly used for representing fixed data sets, function return values, and ensuring data consistency where modification is not required.