Python Tuples, Packing and Unpacking ✅ Exercises

5/5 - (1 vote)

Python provides another type that is an ordered collection of objects which can be accessed by their indices, called a tuple.
Tuples are identical to lists, except for the following properties:

  • Tuples are defined by enclosing the elements in parentheses (()) instead of square brackets ([]).
  • Tuples are immutable, so they’re really unmodifiable lists.

You can’t add elements to a tuple. Tuples don’t have append() or extend() methods.
You can’t remove elements from a tuple. Tuples don’t have remove() or pop() methods.

but You can still:

Find elements, since this doesn’t change the elements.
Use the “in” operator to check if an element exists in the tuple.

Tuples are often used for functions that have multiple return values.

In conclusion, we can say that tuples are a limited version of lists, more efficient in terms of memory use and performance then of lists, that you can’t modify!

How to create a tuple in Python

E.g
volume = (10, 10, 10)

The parentheses are optional when making tuples!

volume = 10, 10, 10

Each value in a tuple does not need to be the same type

Which means you can have a tuple defined like, my_tuple = (1, “string”, 12.3)
This will create a tuple containing an int, string, and float value.

Packing and Unpacking a Tuple

Python offers a powerful assignment tool that maps the right-hand side of values into the left-hand side, without having to access them one by one. This is called unpacking of a tuple of values into a variable.

(x, y, z) = (1, 2, ‘hello’)
print(z)
//hello

or even we can omit the parentheses

x, y, z = 1, 2, ‘hello’
print(z)
//hello

length, width, height = volume

volume = 10, 10, 10
length, width, height = volume
print("The volume is {}x{}x{}".format(length, width, height))

# The volume is 10x10x10

print(volume[0])
# 10

volume = 10, 10, 10
length, width, height = volume

We can combine those two lines of code into a single line that assigns three variables in one go:

length, width, height = 10, 10, 10

Tuples are Comparable

The comparison operators work with tuples!
If the first item is equal, Python goes on to the next element, and so on, until it finds elements that differ.

(1,3,6)<(2,8,9) True

(1,3,6)<(2,1,1) True

Because 1 < 2 and the rest of these numbers really don't matter because that is the most significant digit. On the other hand, if the first one matches, then it has to look at the second one and so on.

The same is for strings, it’s doing a string-by-string comparison.

Sorting Lists of Tuples

We can use the ability to sort a list of tuples to get a sorted version of a dictionary!

>>> colors = {‘red’: 2, ‘blue’: 3, ‘green’: 1, ‘white’: 1, ‘black’: 1}
>>> colors.items()
dict_items([(‘red’, 2), (‘blue’, 3), (‘green’, 1), (‘white’, 1), (‘black’, 1)])

then

>>> sorted(colors.items())
[(‘black’, 1), (‘blue’, 3), (‘green’, 1), (‘red’, 2), (‘white’, 1)]

Also we can write and compose this in a for loop as follows:
for k,v in sorted(colors.items()):
print(k, v)
//
black 1
blue 3
green 1
red 2
white 1

How to sort by value instead of key?

colors = {‘red’: 2, ‘blue’: 3, ‘green’: 1, ‘white’: 1, ‘black’: 1}
new_colors = list()

for k,v in colors.items():
new_colors.append((v, k))

new_colors = sorted(new_colors)
#new_colors = sorted(new_colors, reverse=True) #the reverse flag can be set to request the result in descending order
print(new_colors)

//[(1, ‘black’), (1, ‘green’), (1, ‘white’), (2, ‘red’), (3, ‘blue’)]

or in a short way, using List Comprehensions as follows:

colors = {‘red’: 2, ‘blue’: 3, ‘green’: 1, ‘white’: 1, ‘black’: 1}
print(sorted( [ (v, k) for k,v in colors.items()] ))
[(1, ‘black’), (1, ‘green’), (1, ‘white’), (2, ‘red’), (3, ‘blue’)]

Python Tuple Methods

count()

Returns the number of times a specified value occurs in a tuple.

index()

Searches the tuple for a specified value and returns the position of where it was found.

Why / When to use a tuple instead of a list?

Tuples are useful when You have values that are so closely related that they will always be used together.

Program execution is faster when manipulating a tuple than it is for the equivalent list. When the list or tuple is small, this difference will probably go unnoticed.

For a temporary variable that You will use and discard without modifying.

Tuples refer directly to their elements, therefore this gives tuples a speed advantage for indexed lookups.

Sometimes you don’t want data to be modified. Using a tuple in this case, instead of a list, guards against accidental modification.

If you’re defining a constant set of values and all you need is to iterate through it, use a tuple instead of a list. It will be faster than working with a list.

Conclusions about Tuples in Python

A tuple is an ordered data structure.

A tuple can be indexed and sliced like a list.

Lists are mutable while strings or tuples are not mutable!

Tuple Exercises

Tuples HackerRank exercise

Given an integer n, and n space-separated integers as input, create a tuple t, of those n integers. Then compute and print the result of hash(t).

hash(object)

hash(object) return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

n = int(input())
integer_list = map(int, input().split())

print(hash(tuple(integer_list)))

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

subscribe youtube

Leave a Comment

WebPedia.net