Tuples
Tuple is ordered immutable sequence of ANY objects. They are used when memory counts, when we don't want to change members accidentally, for passing arguments etc.
Syntactically, a tuple is a comma-separated sequence of values. It is not necessary, but it is conventional to enclose tuples in parentheses.
It is not possible to change it's elements after creation. It's like unchangeable list or string where instead of characters are any kind of objects.
Because tuple is sequence it is very similar to list and what is appliable to list and not changing it - will for sure be possible to with a tuple.
Ways to create a tuple:
tuple()
()
(1,)
1,
tuple([1])
# (1,)
(1, 2, 3, [10, 20], 5)
1, 2, 3
Creating a tuple with 1 element requires comma because without it Python consider such expression as logic grouping.
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
In fact parences are not needed, they are just for readability:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Main methods of tuple
🪄 Code:
📟 Output:
That's right - if not counting magic methods - not many at all. Just count
and index
!
Tuple methods
Examples
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Tuple unpacking
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Available only in Python 3:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Tuples vs Lists
The main difference is that tuple is immutable sequence while list is mutable. Some may even call tuple "immutable list" which may have some sense in practice but from architectural point of view is not very correct.
The design purpose of tuple is to store heterogeneous data (objects of different kinds or meaning) while list is intendent to store homogeneous data (objects of the same kind, type, meaning).
Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a set or dict instance.
For heterogeneous collections of data where access by name is clearer than access by index, collections.namedtuple() may be a more appropriate choice than a simple tuple object.
In other words:
use tuple for structure
use list for order/sequencing and processing one by one
Examples
Parts of datetime are different kinds, so it is tuple:
🪄 Code >>> and 📟 Output:
🪄 Code:
📟 Output:
Values is result of range() are all of the same type, so it is list (in Python 2):
🪄 Code >>> and 📟 Output:
🪄 Code:
📟 Output:
* Coordinates:
Last updated