Immutable Data Type, Tuple
A tuple
is a data type that stores multiple values in order, similar to a list
, but once created, its content cannot be changed due to its immutability
.
This immutability makes tuples useful for safely storing values that must not be altered, such as coordinates of a specific location or color values.
How do you define a tuple?
A tuple is created by enclosing elements in parentheses ()
and separating each element with a comma ,
.
Tuple Declaration Example
my_tuple = (1, 2, 3)
print(my_tuple) # (1, 2, 3)
You can also define a tuple by omitting the parentheses and simply separating the elements with commas.
Tuple Declaration without Parentheses Example
my_tuple = 1, 2, 3
print(my_tuple) # (1, 2, 3)
How do you use a tuple?
Tuples are used to safely store values in a program that should not change.
For example, in a map-related program, you can use a tuple to store the latitude and longitude of a specific location.
Tuple Example
# Latitude and longitude of New York
coordinates = (40.7128, 74.0060)
# Print the first element, 40.7128
print("Latitude of New York:", coordinates[0])
# Print the second element, 74.0060
print("Longitude of New York:", coordinates[1])
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.