The Noobs of Python: Ep.2.4 - Tuples ! and Unpacking Tuples!

Q: I heard Tuples are pretty basic, similar to a List without all the features. Why cover them?
A: There is a purpose for Tuples, this is where we get our start and go in-depth !

A tuple is specified as a comma-separated list of values, which may be enclosed in parentheses.
tuple( 'item',) Similar to lists, tuples are sequences of arbitrary items. Unlike lists, tuples are immutable, meaning you can’t add, delete, or change items after the tuple is defined. So, a tuple is similar to a constant list. They are used everywhere in Python, because they allow for patterns that are hard to reproduce in other languages. The values need not all be of the same type. A value can also be another tuple.

Here are some examples:

>>> # Create a Tuple
>>> empty_tuple = ()
>>> empty_tuple
()


>>> # A One item tuple
>>> Level1 = 'Kreestuh',
>>> Level1
('Kreestuh',)


>>> # Multiple element tuple 
>>> # Follow all elements except the last element with a comma
>>> LevelOne = 'Kreestuh', 'Wendell', 'Grizzle'
>>> LevelOne
('Kreestuh', 'Wendell', 'Grizzle')
>>> L1Tech = ('Level', 'One', 'Tech')


>>> #You can assign multiple variables at once
>>> a, b, c = L1Tech
>>> a
'Level'
>>> b
'One'
>>> b
'One'
>>> c
'Tech'
>>>

Q: Yeah, that's kind of what I expected, Kinda boring... But what about this unpacking? What's it about?
A: I will cover more on unpacking and it's use in a post below ! We will use Tuple as records and storing coordinates and other cool things !

Code_On_Code_Warrioirs

2 Likes

So we talked about tuples as “immutable lists”, but that is short selling them. Tuples do double-duty: they can be used as immutable lists and also as records with no field names.

Tuples hold the data for one field and the position of the item gives its meaning. If you think of a tuple just as an immutable list, the quantity and the order of the items may or may not be important, depending on the context. But when using a tuple as a collection of fields, the number of items is often fixed and their order is always vital. Below are some examples of tuples being used as records:

>>> # Variables for coordinates and other statistical info
>>> 
>>> mt_rushmore = (43.8789472, -103.459825)
>>> 
>>> city, year, pop, rnk, area = ('Warsaw', 2017, 38563468, 37, 312679)
>>> 
>>> trav_ids = [('EST', '233'), ('GIB', '292'), ('FRA', '250')]
>>>

The first variable is the Latitude & Longitude information for Mt Rushmore, The second is statistical information on Warsaw, Poland, The third is the Country and Country Code pairs. Below is an example of using a for loop to

>>> 
>>> for passport in sorted(trav_ids):
	print('%s/%s' % passport)

	
EST/233
FRA/250
GIB/292
>>>

The % formatting operator understands tuples and treats each item as a separate field. Here is another example
The for loop knows how to retrieve the items of a tuple separately this is called “unpacking”. Here we are not interested in the second item, so it’s assigned to _ , a dummy variable.

>>> 
>>> for country, _ in trav_ids:
	print(country)

EST
GIB
FRA
>>> 
>>>

More on Tuple Upnpacking below !

Here are some more examples and a jump into Tuple unpacking !

>>> # Here we assigned the variables in a single statement
>>> city, year, pop, rnk, area = ('Warsaw', 2017, 38563468, 37, 312679)
>>> 
>>> print(city, year)
Warsaw 2017
>>> print(city)
Warsaw
>>> print(rnk)
37
>>> print(area)
312679
>>> 
>>> # Here is a simple Tuple unpacking
>>>
>>> mt_rushmore = (43.8789472, -103.459825)
>>> 
>>> Longitude, Latitude = mt_rushmore
>>> 
>>> Longitude
43.8789472
>>> Latitude
-103.459825
>>>

Tuple unpacking works with any iterable object. The only requirement is that the iterable yields exactly one item per variable. Another example of tuple unpacking is prefixing an argument with a * when calling a function here are some examples below:

>>> # Using * to grab excess items
>>> 
>>> a, b, *rest = range(7)
>>> a, b, rest
(0, 1, [2, 3, 4, 5, 6])
>>> c, d, *E = range(15)
>>> c, d, E
(0, 1, [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
>>> f, g, *blank = range(2)
>>> f, g, blank
(0, 1, [])
>>>

This is conceptually called parallel assignment, we can also use the * to be assigned to exactly 1 variable in any place here is an example of that :

>>> 
>>>
>>> a, *b, rest = range(4)
>>> a, b, rest
(0, [1, 2], 3)
>>>
>>> *d, e, f, g = range(10)
>>> d, e, f,g
([0, 1, 2, 3, 4, 5, 6], 7, 8, 9)
>>>

In the next post we will cover Nested Tuple unpacking and round it up for this Ep series with Named Tuples. If you have any questions, please feel free to comment or post your code !

Code_On_Code_Warriors !

Nested Tuple Unpacking :

Here I'll give a brief example of Nested Tuple unpacking by showing an example of City, Year, Population and the Latitude, Longitude coordinates within a nested tuple. Code is below:

# Variable with City, Year, Population, and in a Tuple Coordinates

metro_areas = [('Warsaw', 2017, 38563468, 312679, (52.21667, 21.03333)),
		('Prague', 2017, 2156097, 496, (50.083333, 14.416667)), 
		('Mexico City', 2017, 8918653, 1485, (19.433333, -99.133333)),
		('New York City', 2017, 8537673, 13318, (40.7127, -74.0059)), ]

# A for loop is used to unpack the data in a format we choose. 

for name, _, pop, area, (latitude, longitude) in metro_areas:
	if longitude >= 0:
		print(name, pop, area, (latitude, longitude))

Warsaw 38563468 312679 (52.21667, 21.03333)
Prague 2156097 496 (50.083333, 14.416667)

We used the for loop to return the name, population, area and the coordinates if the longitude was equal or greater than 0, Pretty simple ! In the following example we'll show just retuning the name and coordinates using the same variable:

for name, _, _, _, (latitude, longitude) in metro_areas:
	print(name, (latitude, longitude))

Warsaw (52.21667, 21.03333)
Prague (50.083333, 14.416667)
Mexico City (19.433333, -99.133333)
New York City (40.7127, -74.0059)

Again using a dummy variable _, to skip over the result we wish not to see, we simply get the city and coordinates in a tuple !

1 Like