Python Tuples, Packing and Unpacking ✅ Exercises

python tuples

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.

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.

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.

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 sort those two lines of code into a single line that assigns three variables in one go:

length, width, height = 10, 10, 10

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.
  • 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.

Hello there!

I hope you find this post useful!

I'm Mihai, an 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!

Leave a Reply

Your email address will not be published. Required fields are marked *