A tuple is a built-in data type used to store multiple items in a single, ordered, and immutable collection. Tuples are like lists, but with the one big difference of not being able to be changed after creation. This makes tuples safer than lists and use up less memory than lists. This makes them great for data integrity where the data shouldn't be modified, like geographic coordinates or RGB values. Another key aspect of tuples is that they are hashable and can be used as keys in dictionaries or stored in sets.
Tuples
Tuples in Python
Creating Tuples
Tuples are defined using parentheses () instead of square brackets []. Although you can also omit the parentheses but this makes the code less clear. If you only have 1 item in your tuple, you still need to include a comma.
my_tuple = (1, 2, 3)
my_tuple = 1, 2, 3
single_item = (5,) # Single item tuple
not_a_tuple = (5) # Just an integer
Accessing Tuple Items
Tuples are 0 indexed and ordered, which differs them from JavaScript sets. Slicing like you would on a list also works for tuples.
colors = ("red", "green", "blue")
print(colors[1]) # Output: green
print(colors[:2]) # Output: ('red', 'green')
Tuple Unpacking
You can assign each value of a tuple to a variable in one line by putting comma separated variables equal to the tuple. This will assign the 1st variable to the 1st value in the tuple, 2nd variable to the second value, etc. Underscores (_) can also be used to ignore/skip values you do not want to assign to variables.
person = ("Adam", 34)
name, age = person
print(name) # Adam
print(age) # 34
You can also use _ to ignore values:
name, _, job = ("Bob", 25, “Director”)
print(name) # Bob
print(job) # Director
Nesting
Tuples can hold other tuples, lists, or mixed types. While the tuple is immutable, mutable elements inside it (like lists) can still be changed:
nested = (1, [2, 3], ("a", "b"))
print(nested[1][0]) # Output: a
nested[1][0] = 99
print(nested[1][0]) # Output: 99
Tuple Methods
Tuples have only two built-in methods.
.count(x): Returns the number of times x appears..index(x): Returns the first index of x.
numbers = (1, 2, 3, 2)
print(numbers.count(2)) # 2
print(numbers.index(3)) # 2