Python Tuple Unpacking

python-tuple-unpacking-ipcisco-1

To create a tuple, firstly we assign values to this tuple. In other words, we do Python Tuple Packing. In this lesson, we will do the reverse of this, Python Tuple Unpacking.  With Tuple Unpacking, we will extract the values back into variables.

 

So, let’s firstly check do Python Tuple Packing. Here, we will add values to the tuple, we will create tuple. Out tuple example will include some of the characters of the lord of the rings.

 

characters = ("Aragorn", "Legolas", "Gimli") 
print(characters) 

 

The output of this Python Tuple Packing code will be like below:

 

('Aragorn', 'Legolas', 'Gimli')

 

Now, let’s do Python Tuple Unpacking. We will do this with the below example.

 

characters = ("Aragorn", "Gimli", "Legolas")    # python tuple packing line
(human, dwarf, elf) = characters    # python tuple unpacking line
print("Human :", human)
print("Dwarf :", dwarf)
print("Elf :", elf)

 

The output of this code will be like below:

 

Human : Aragorn
Dwarf : Gimli
Elf : Legolas

 

You can also wtach the video version of this lesson!

 

python-tuple-unpacking-ipcisco-1

 

Here, the number of the variables and the number of the memebrs in tuple must be same. If these numbers are not same, then we can use asterisk (*). If we use this sign, then the remaining values are assigned same. Let’s do an example for this.

 

characters = ("Aragorn", "Gimli", "Legolas", "Elrond", "Galadriel")   
(human, dwarf, *elf) = characters   
print("Human :", human)
print("Dwarf :", dwarf)
print("Elf :", elf)

 

In the output of this Python Tuple Unpacking example code will be like below:

 

Human : Aragorn
Dwarf : Gimli
Elf : ['Legolas', 'Elrond', 'Galadriel']

 

python-tuple-unpacking-ipcisco-2

 

As you can see here, because of the fact that we use asterisk (*) with “elf”, the tuple members after it all defined as elf.

 

Like Python Tuple Packing, you can use Tuple Unpacking for different purposes. You can extract the values into variables and use them in your code.

 

Back to: Python Programming Course > Python Tuples

Leave a Reply

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

Contact

  • info@ipcisco.com
IPCisco is the Winner! “Best Certification Study Journey of 2019!”

Cisco-ITBlogAwards-2019-Winner-IPCisco-k