Tuples
Code sample link: https://replit.com/@jjoco/python-tuples
Tuples, like lists, contain a record of values. Unlike lists, however, tuples cannot be changed after they have been created; you cannot remove or add more elements into a tuple.
Why use tuples
When we know what values are going to be in collection, it is generally better to use tuples than lists. Tuples are also generally faster and memory efficient to create and read than lists since tuples have constant size. Unlike lists, in which it is almost mandatory practice to have lists contain only one data type, it is an okay practice to have multiple types in a tuple. This is why each element in a dictionary.items()
call is a 2-tuple, in which the key and value types may not coincide.
So, if you wanted to maintain a running list of users with fields age
, name
, and id
, you may not need to create a separate class for User
. The list can look something like
1 |
|
Creating a tuple
You can create a tuple using parentheses ()
like so:
1 2 |
|
Accessing a tuple element
Like lists, you can access a value or group of values via indexing:
1 2 3 |
|
Getting the length of a tuple
To get the number of elements in a tuple (ie. its length), use the len
function:
1 |
|
my_tuple = (2, True, False, "hello")
, then len(my_tuple)
would be 4
.
Unpacking a tuple
Though it is not as common for lists and dictionaries to be unpacked, unpacking a tuple (ie assigning values within the tuple to external variables) is much more common due to its immutability:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Recall that when we process a dictionary's items using dictionary.items()
, we use syntax:
1 2 3 4 |
|
.items()
is a list of 2-tuples, and we're unpacking each 2-tuple item into some_key
and some_val
.