= np.vstack((arr1, arr2)) stacked_array
Tuples
Unit 05
A new data type: tuples
We have come across tuples a few times during our first units without explaining them in more detail. For example, think back to exercise #03-02 where we applied the numpy functions concatenate
and vstack
:
Mind the double parentheses. What do they mean?
Consider the following example:
# create a list and a tuple
= [1, 2, 3]
list1 = (1, 2, 3)
tuple1
# extract elements from list and tuple
print(f"This is list element 1: {list1[0]}")
print(f"This is tuple element 2 & 3: {tuple1[1:3]}")
This is list element 1: 1
This is tuple element 2 & 3: (2, 3)
# mutate list
0] = -99
list1[print(f"List element 1 got changed to: {list1[0]}")
List element 1 got changed to: -99
# try to mutate tuple
try:
0] = -99
tuple1[except:
print("Ooops, upon trying to change a tuple element, we got an error!")
Ooops, upon trying to change a tuple element, we got an error!
Tuples are immutable
Tuples are in fact very similar to lists. They are both sequences that can contain elements of different data types, which in turn can be accessed by indexing.
Their major difference is that lists are mutable, and tuples are immutable. Once a tuple is created, you cannot change single tuple elements any more. This makes tuples useful for representing collections of items that should not be altered.
Packing of tuples
We have just learned one way of creating a tuple, by writing a comma-separated sequence of elements that is enclosed by parentheses:
= (1, 2, 3) tuple1
While the above is the most common approach to creating a tuple, the following approaches are also valid:
= 4, 5, 6 # you can omit the parentheses
tuple2 = tuple() # using a function call tuple3
Unpacking of tuples
A very useful feature of python is that you can have a tuple on the left hand side of an assignment statement. Consider the following example:
= (3, 4) # Tuple packing
point = point # Tuple unpacking x, y
Note that it is common practice to use parentheses in tuple packing, while it is common practice to omit the parentheses in tuple unpacking.
This feature of unpacking tuples is often used by functions that return more than one value. Consider this example from Fabien Maussion:
def split_email_address(email):
"""Splits an email address in username and domain.
Parameters
----------
email : str
the email string
Returns
-------
(username, domain): tuple of strings
"""
return tuple(email.split('@'))
= split_email_address('john.doe@uibk.ac.at')
username, domain print(username)
print(domain)
john.doe
uibk.ac.at