Hello everyone, and Welcome back to Digital Academy – the Complete Python Development Tutorial for Beginners.
In the previous tutorial, you may have discovered in-depth use about Lists, in Python. This kind of Data Types is used, when you want to store values and access them, in a very particular order.
In this brand new video, you will now discover another Data Type: Tuples! Be sure to stick around, and watch until the end of this video, if you want to discover various actions and methods that you can perform on tuples, and practice.
Please, Do not forget to smash that Like button, for the YouTube algorithm – since it does really help supporting us, and providing new FREE content, once a week! You may also want to follow Digital Academy, on our other social platforms: Facebook, Instagram, Twitter and Patreon. This way, we could: stay in touch, grow this community, then share and help each other, throughout this exciting journey, OUR journey! Are you interested to be part of this community? All the Links are in the description below! Now, Let’s play this video …
Definition
Python provides another kind of Data Type, called a tuple. Tuples are a lot like Lists in Python, and are used to collect objects in order. Consequently, everything you have learned about Lists is true, for tuples as well. A tuple in Python is an ordered collection of values, which is accessed by index, and contains any sort of objects – like: numbers, strings, lists, or even other nested tuples. Lists and Tuples can contain duplicate members! Except that tuples are immutable, which means you theoretically cannot: add, delete or change items inside the tuple – once created. Nonetheless, you can iterate through a tuple, with a simple for loop as well.
- Tuples are ordered – Tuples maintains a left-to-right positional ordering, among the items they contain.
- Accessed by index – Items in a tuple can be accessed and sliced using an index, inside square brackets.
- Tuples can contain any sort of object – It can be numbers, strings, lists and even other nested tuples.
- Tuples are immutable – you cannot add, delete, or change items after the tuple has been defined.
Why use a tuple then, instead of a list?
- Program execution is faster when manipulating a tuple, than it is for the equivalent list.
- Sometimes you do not want data to be modified. If the values in the collection are meant to remain constant for the life of the program, using a tuple instead of a list protects your data from accidental modification (add / remove).
- There is another Python data type called a Dictionary, which requires as keys, a value that is of an immutable type. A tuple can be used for this purpose, whereas a list cannot be.
Awesome, you know what a tuple can be used for! But, how to declare a tuple, pack and unpack some values, or even access specific items? Let’s find out, throughout these next sections.
Creating a Tuple
Unlike Lists in Python, Tuples are defined by enclosing the elements in parentheses () – instead of square brackets [].
my_tuple = ("Learn", "Python", "with", "Digital Academy", 1, 2, 3)
You can create a tuple by placing a comma-separated sequence of items, in parentheses. Thus, a tuple containing zero items is called an empty tuple, and you can create one with empty parentheses. The items of a tuple do not have to be the same type. For instance, the following tuples contain integers, strings, float, or boolean values.
# Empty tuple
my_tuple = ()
# A tuple of integers
my_tuple = (1, 2, 3)
# A tuple of strings
my_tuple = ('red', 'green', 'blue')
# A tuple with mixed data types
my_tuple = (1, 'abc', 1.23, True)
Syntactically, a tuple is just a comma-separated list of values. You do not necessarily need the parentheses, to create a tuple. It is the trailing commas that really define a tuple. But, using parentheses does not hurt, because they help make the tuple more visible.
# A tuple without parentheses
my_tuple = 1, 'abc', 1.23, True
Singleton Tuple
Since parentheses are also used to define operator precedence in expressions, Python evaluates the expression 7 as simply the integer 7, and creates an int object. To tell Python that you really want to define a singleton tuple, with only one value, include a trailing comma “,” – just before the closing parenthesis.
# Not a tuple
my_tuple = (7)
type(my_tuple) # <type 'int'>
# Tuple
my_tuple = (7,)
type(my_tuple) # <type 'tuple'>
The tuple() Constructor
It is also possible to use the tuple() constructor when you want to create a tuple. And, you can convert other data types to tuple, using Python’s tuple constructor as well.
my_tuple = tuple(("apple", "banana", "cherry"))
# Convert list -> tuple
my_tuple = tuple([1, 2, 3])
# my_tuple = (1, 2, 3)
# Convert string -> tuple
my_tuple = tuple('abc')
# my_tuple = ('a', 'b', 'c')
Tuple Packing & Unpacking
Tuple Packing
When a tuple is created, the items in the tuple are packed together, into an object. In this example, the values ‘red’, ‘green’, ‘blue’ and ‘yellow’ are packed together, into a tuple.
my_tuple = ('red', 'green', 'blue', 'yellow')
# my_tuple = ('red', 'green', 'blue', 'yellow')
Tuple Unpacking
When a packed tuple is then unpacked, the individual items are unpacked and assigned to the items you defined. In the below example, the tuple “my_tuple” is unpacked into the variables ‘red’, ‘green’, ‘blue’ and ‘yellow’ so you can access each one of them, individually. When unpacking, the number of variables on the left must match the number of items in the tuple.
my_tuple = ('red', 'green', 'blue', 'yellow')
(red, green, blue, yellow) = my_tuple
print(red) # red
print(green) # green
print(blue) # blue
print(yellow) # yellow
Here are some very common errors, during tuple unpacking – too many arguments, or not enough values to unpack!
my_tuple = ('red', 'green', 'blue', 'yellow')
(red, green) = my_tuple
# ValueError: too many values to unpack
my_tuple = ('red', 'green', 'blue')
(red, green, blue, extra) = my_tuple
# ValueError: not enough values to unpack (expected 4, got 3)
Eventually, you may also want to unpack only some values from your tuple, but do not store all of its items inside each variable. Fortunately, Python offers this feature, using “_”. This way, each item is mapped into a new variable when it has one affected, and store its value so you can access it later.
my_tuple = ('red', 'green', 'blue', 'yellow')
red, green, blue, _ = my_tuple
Awesome! But, you do not have any idea when using packing and unpacking methods might be useful for you? Here are a few examples in which you may want to pack and unpack a tuple.
Usage
Tuple unpacking comes handy when you want to swap values of two variables, without using a temporary variable.
a = 1
b = 99
# Swap values
a, b = b, a
print(a) # 99
print(b) # 1
While unpacking a tuple, the right side can be any kind of sequence: tuple, string or list. Typically, you may also apply any method on your variable that returns this kind of sequence, then proceed with unpacking. For instance, this below example will split a string representing an email address into its user and domain, so you can access them individually.
# Split an email address
addr = 'digital.academy@free.fr'
user, domain = addr.split('@')
# user = digital.academy
# domain = free.fr
Accessing an Item
You can access individual items in a tuple using an index in square brackets, or using the unpacking method. Note that tuple indexing in Python starts from 0. The indices for the elements in a tuple are illustrated as below:
my_tuple = ('red', 'green', 'blue', 'yellow', 'black')
print(my_tuple[0])
# Prints red
print(my_tuple[2])
# Prints blue
You can access a tuple by negative indexing as well. Negative indexing counts backward, from the end of the tuple. So, my_tuple[-1] refers to the last item, my_tuple[-2] is the second-last, and so on. But be careful not to access an element outside of your tuple, or you would get an IndexError: tuple index out of range.
my_tuple = ('red', 'green', 'blue', 'yellow', 'black')
print(my_tuple[-1])
# Prints black
print(my_tuple[-2])
# Prints yellow
Tuple Slicing
Okay, But how you would access a range of items, from your tuple? You need to slice a tuple using the slicing operator. Tuple slicing is similar to List slicing, in which you will specify the start and end indexes with an optional step size. Each parameter can be positive or negative indexing values. Do you want to discover more about Python slicing Operators? Please, Check out our Blog, and the video about Lists in Python.
my_tuple = ('a', 'b', 'c', 'd', 'e', 'f')
print(my_tuple[2:5]) # ('c', 'd', 'e')
print(my_tuple[0:2]) # ('a', 'b')
print(my_tuple[3:-1]) # ('d', 'e')
Adding / Updating Tuple
As you know: Tuples are immutable. Once a tuple has been created, it cannot be modified afterwards or it would trigger an error: TypeError exception. That’s what it costs if you want to increase security and speed when manipulating tuples!
my_tuple = ('red', 'green', 'blue')
my_tuple[0] = 'black'
# Triggers TypeError: 'tuple' object does not support item assignment
Consequently, when you use this kind of data type, you are not supposed to add, update or remove items from a tuple. But, there is a workaround: You can convert the tuple into a list, change the list, then convert the list back into a tuple!
my_tuple = ('red', 'green', 'blue') # my_tuple = ('red', 'green', 'blue')
my_tuple = list(my_tuple) # my_tuple = ['red', 'green', 'blue']
my_tuple[0] = 'black' # my_tuple = ['black', 'green', 'blue']
my_tuple = tuple(my_tuple) # my_tuple = ('black', 'green', 'blue')
Note: The tuple immutability is applicable only to the Top level of the tuple itself, not to its contents. For example, a list inside a tuple can be changed as usual with indexing, without even converting the tuple into a list first.
my_tuple = (1, [2, 3], 4)
my_tuple[1][0] = 'abc'
# my_tuple = (1, ['abc', 3], 4)
Removing an Item
Tuples cannot be modified, because they are immutable. So, obviously, you cannot directly delete any item, either. But, the same way you did to update an item, you can: convert the tuple into a list, delete an item, then convert the list back into a tuple. And if you don’t need your tuple anymore, you can completely delete the tuple itself using the del keyword.
my_tuple = ('red', 'green', 'blue') # my_tuple = ('red', 'green', 'blue')
my_tuple = list(my_tuple) # my_tuple = ['red', 'green', 'blue']
del my_tuple[0] # my_tuple = [green', 'blue']
my_tuple = tuple(my_tuple) # my_tuple = ('green', 'blue')
del my_tuple
Checking existence
To determine whether a value is or is not in a tuple, you can use “in” and “not in” membership operators combined with Python if statement. If you need help using these kind of statements please check out the suggested videos: on Python operators and conditionals, in Python
my_tuple = ('red', 'green', 'blue')
# Check for presence
if 'red' in my_tuple:
print('red in my_tuple')
# Check for absence
if 'yellow' not in my_tuple:
print('yellow not in my_tuple')
Iterating through a Tuple
Tuple is a very useful and a widely used data structure. As a Python developer, you will often be in situations where you will need to iterate through a tuple, while you perform some actions on its items. Fortunately, the most common way to iterate through a tuple, is with a for loop.
my_tuple = ('red', 'green', 'blue')
for item in my_tuple:
print(item)
# OUTPUT:
# red
# green
# blue
This works well if you only need to read the items of a tuple. But, if you want to update them, you need the indexes. A common way to do that, is to combine the range() and len() functions altogether – or use the enumerate() function. For instance, this loop iterates through the tuple and print out each item. If you do not know how to use the range() function nor how the enumerate() function works, please check out the suggested video about: Python FOR Loops.
my_tuple = ('red', 'green', 'blue')
for index, item in enumerate(my_tuple):
print(index, item)
# OUTPUT:
# 1, red
# 2, green
# 3, blue
Tuple Length
Eventually, you may want to find how many items a tuple has. In that case, you do not have to iterate through the entire tuple and count each item, but simply use the function len() – which returns the number of items inside your tuple.
my_tuple = ('red', 'green', 'blue')
print(len(my_tuple)) # OUTPUT: 3
Tuple Merging and Sorting
Although tuples are not changeable, you may sometimes want or need to merge two tuples, so that you can have all of your data located, in the same variable. Or, even update its items, with new values. Fortunately, 2 tuples can be joined using the concatenation operator (+), or the augmented assignment operator (+=) – to combine all of the items. If you need help using operators, check out our Blog and the video about: Python Operators.
Notice: Tuples keep duplicate members, so this method does not overwrite existing values, and add them at the end.
my_tuple = ('red', 'green', 'blue')
# Concatenation operator
my_tuple = my_tuple + (1,2,3)
# my_tuple = ('red', 'green', 'blue', 1, 2, 3)
# Augmented assignment operator
my_tuple += (1,2,3)
# my_tuple = ('red', 'green', 'blue', 1, 2, 3)
Awesome! But how would you proceed, if you need to rearrange items inside of your tuple? There are two methods to sort a tuple: using a built-in method, or convert it into a mutable object first, then rearrange it.
Method 1: Use the built-in sorted() method that accepts any sequence object as parameter.
my_tuple = ('red', 'green', 'blue', 'yellow')
my_tuple = tuple(sorted(my_tuple))
# my_tuple = ('blue', 'green', 'red', 'yellow')
Method 2: Convert a tuple to a mutable object like list, gain access to a sorting method call, and convert back to tuple.
my_tuple = ('red', 'green', 'blue', 'yellow')
my_list = list(my_tuple) # Convert tuple to list
my_list.sort() # Sort the entire list
my_tuple = tuple(my_list) # Convert back to tuple
# my_tuple = ('blue', 'green', 'red', 'yellow')
Practicing with Tuples
Awesome, It’s your time to practice now. All of these instructions are in the description bellow, and will combine all the methods you have discovered during this class.
In this exercise, you will have to declare a tuple with the values ‘red’, ‘green’, ‘blue’, ‘yellow’ and ‘black’. First, you will have to unpack this tuple into multiple variables, within their respective names. Then, if the tuple has a value ‘green’ and that it corresponds to the 2nd item, update the variable yellow with the value ‘orange’, then change the order of the items, by swaping the values of the variables red and black together. Finally, you will pack all these variables into a new tuple, and iterate through the items until you meet the value ‘orange’. Once you have encountered this item: convert this tuple into a list, use its index to update the value ‘orange’ back to its original value ‘yellow’, and convert it back to your tuple. Then, break out of the loop once it’s done. Eventually, you will use the slicing operator so that you do not keep the last value, and print out the resulting tuple. Please, do tell me in the comment: What did you get?
SOLUTION
Here is a solution, and may vary from yours. First let’s declare a variable my tuple, with the values ‘red’, ‘green’, ‘blue’, ‘yellow’ and ‘black’. Then, unpack this tuple into variables with their respective names. Now, you will check whether an item green exists inside my tuple, and if it corresponds to the second item. If it does, you will enter the if statement and change the value of the variable yellow, with the value ‘orange’. Plus, swap the two variables red and black together, so that the variable red becomes ‘black’, and the variable black becomes ‘red’. Before proceeding with the for loop, you will pack back all the variables into a new tuple. Then iterate through its items using for loop and enumerate function, so that you can access both the current value, and its index in the tuple. As soon as you encounter the value ‘orange’, you will convert your tuple into a list. Update the item located at this index, with the new value ‘yellow’. Then convert it back into your tuple, so you can exit the loop straight away. Finally, you will use the slicing operator so you keep all of the items inside your tuple, except the last one. Running this program should give you the tuple ‘black’, ‘green’, ‘blue’, and ‘yellow’ – since the last one has been removed.
my_tuple = ('red', 'green', 'blue', 'yellow', 'black')
red, green, blue, yellow, black = my_tuple # Unpack values
if 'green' in my_tuple and my_tuple[1] == 'green':
yellow = 'orange' # yellow = 'orange'
red, black = black, red # red='black', black='red'
my_tuple = (red, green, blue, yellow, black) # ('black', 'green', 'blue', 'orange', 'red')
for index, colour in enumerate(my_tuple): # Iterate through items (index, value)
if colour == 'orange':
my_list = list(my_tuple) # Convert into list (mutable)
my_list[index] = 'yellow' # Update value located at index
my_tuple = tuple(my_list) # Convert back inot tuple (immutable)
break # Break out of the Loop
# Do not keep the last item
my_tuple = my_tuple[:-1] # my_tuple = ('black', 'green', 'blue', 'yellow')
Congrats! You just wrote your first complex program using tuple, and some of the operations you can perform on it. Please tell me in the comments if you found the answer or have any question? And check out our Blog, if you want more examples.
As you have seen in this example, tuples are immutable so you will iterate through its items, faster than in a list. And, because of its immutability, you are not supposed to add, update or remove values. Nonetheless, if you convert your tuple into a mutable sequence, there are many ways to bypass this restriction.
Methods & Functions
Python has a set of other built-in methods that you can call on tuple objects. Some have been discovered throughout this video, so you can add or update values, even get or remove a specific item. But, you may also want to merge or sort a tuple, count how many times an item is present inside your tuple, gets its min or max values, and even get the index of a specific item? Of course, all of that is possible in a very simple way, using these built-in methods. If you are interested to learn more about these methods, you can find more information on the Python documentation website.
Method | Description |
---|---|
count() | Returns the count of specified item in the tuple |
index() | Returns the index of first instance of the specified item |
Python also has a set of built-in functions that you can use with tuple objects.
Method | Description |
---|---|
all() | Returns True if all tuple items are true |
any() | Returns True if any tuple item is true |
enumerate() | Takes a tuple and returns an enumerate object |
len() | Returns the number of items in the tuple |
max() | Returns the largest item of the tuple |
min() | Returns the smallest item of the tuple |
sorted() | Returns a sorted tuple |
sum() | Sums items of the tuple |
tuple() | Converts an iterable (list, string, set etc.) to a tuple |
Conclusion
In this tutorial, you have learned in-depth use about Tuples, in Python. This kind of Data Types is used, when you want to store a few items of any Data Type in a very specific order, access its values faster than with a List, plus add some extra security to prevent accidental modification of its values. Consequently, you should now be able to: create a tuple, pack and unpack a few values, or even search for a specific item. Thus, Tuples should not be a secret anymore, and you can start using them in your Python program, straight away!
In the next tutorial, you will discover another Data Type, in details: Sets! So, do not waste any minute of it, and join us in the next episode! If you liked this video, please: do not forget to give a thumb up, and subscribe our channel!
– Digital Academy™ 🎓
📖Complete Python Development Course for Beginners
#Python #Tutorial #Beginners #Tuple
***
♡ Thanks for watching and supporting ♡
Please Subscribe. Hit the notification bell.
Like, Comment and Share.
***
♡ FOLLOW US ♡
✧ http://digital.academy.free.fr/
✧ https://twitter.com/DigitalAcademyy
✧ https://www.facebook.com/digitalacademyfr
✧ https://www.instagram.com/digital_academy_fr
✧ https://www.youtube.com/c/DigitalAcademyOnline
***
♡ SUPPORT US ♡
✧ http://digital.academy.free.fr/join
✧ http://digital.academy.free.fr/donate
✧ http://digital.academy.free.fr/subscribe
✧ https://www.patreon.com/digital_academy
✧ https://www.buymeacoffee.com/digital_academy