Python Tuples (Tuple)
Tuples are another very important data sequence type in Python. They are very similar to lists, but with one key difference: tuples are immutable.
What is a Tuple?
A tuple is an ordered and immutable collection. Once created, you cannot modify, add, or delete elements in the tuple.
Creating Tuples
Tuples are defined using parentheses (), with elements separated by commas ,.
Note: Creating a tuple with only one element
If you want to create a tuple containing only one element, you must add a comma , after that element.
Accessing Tuple Elements
Accessing tuple elements works exactly the same as with lists, through indexing and slicing.
Tuples are Immutable
This is the core difference between tuples and lists. Any attempt to modify a tuple will result in a TypeError.
Why Use Tuples?
Since lists are more feature-rich, why do we need tuples?
-
Data Integrity: Since tuples are immutable, you can ensure their contents won't be accidentally modified during program execution. This makes code safer and more predictable. Perfect for use as constant collections.
-
Performance Optimization: In most cases, tuples are slightly faster to process than lists and consume less memory.
-
Can be Used as Dictionary Keys: Because tuples are immutable (hashable), they can be used as dictionary keys. Lists are mutable and cannot be used as dictionary keys.
Tuple Methods
Because tuples are immutable, they have very few methods - only two:
tuple.count(x): Returns the number of times elementxappears in the tuple.tuple.index(x): Returns the index of the first occurrence of elementxin the tuple.
Tuple Unpacking
This is a very convenient and Pythonic feature that allows you to assign elements of a tuple to multiple variables.
This feature is particularly useful when functions return multiple values, as a function's multiple return values are actually packaged as a tuple and returned.