Skip to main content

Tuple Unpacking in Python

Tuple Unpacking

Tuple is a collections of data (of different data types) and are created by specifying the data (or variables) inside round brackets. We can also call this as Tuple packing. See more about working with tuples.

So, what is tuple unpacking? As the name suggests unpacking the data from a tuple into variables is called tuple unpacking.

Let's have a quick look at the creation of a tuple (packing) and unpacking of a tuple. 

Tuple unpacking in Python

In the above example, 
  • Line - 2: Creating variable num_one to store a number (1).
  • Line - 4: Creating variable char_one to store a string (ONE). 
  • Line - 8: Creating a tuple by mentioning the variables created inside round brackets (num_one, char_one). This can also be done by directly providing the data inside round brackets (1, "ONE").
  • Line - 11: Unpacking the tuple, unpacking the data in a tuple into different variables. First element in the tuple would be assigned to the first variable and second element in the tuple would be assigned to the second variable. 
  • Lines - 13 & 14: Printing the data from the unpacked variables.

We have not used round brackets to do the tuple unpacking. But, this should work in the same way even if we specify the variables inside round brackets for unpacking the data from a tuple. 

Tuple unpacking in Python

In the above example, we are unpacking a tuple with two elements to two different variables. Similarly, we can do the same for any number of equal variables. 

What to do if there are more number of elements in the tuple than the variables? 

Tuple unpacking would fail with "ValueError: too many values to unpack". 

Tuple unpacking in Python

Tuple Unpacking  - Value Error

So, how to deal with these kind of issues? Well, there isn't straight forward answer to this and depends on why we are moving more number of elements (from tuple) to a less number of variables. 

If this is intended and group of tuple elements should be assigned to a single variable (as list), this can be done by using asterisk (*) before the variable. 

Let's take a look at different example to understand this better. 

Tuple Unpacking in Python

In the above example, 
  • Tuple has three elements.
    • First element is the color. 
    • Second and Third elements are the fruits in the specific color. 
So the requirement here is to create a variable called 'color' to hold the color from tuple and create a list called 'fruits' to hold the list of fruits from tuple. 

If we use the variable names color and fruits as it is, ValueError would be thrown. So, we are using asterisk (*) before 'fruits' which needs to store the fruits as a list. 

Result here would be, 
  • Mapping of first variable to the first element (no asterisk for color, so would consider as one to one mapping). 
  • Mapping of second variable (list) to the remaining elements in the tuple. 
There are few points to consider here.
  • An empty list would be created if there is no corresponding data present in the tuple.     
Tuple unpacking in Python

  • A list would be created with just one element if there is only one corresponding entry in the tuple. Unlike the the variable with the type of data (if asterisk is not used).
Tuple unpacking in Python

  • A list would be created with multiple elements if there are multiple entries in the tuple. 
Tuple unpacking in Python

One thing to note here is a list variable doesn't necessarily be the second or last, this can be in any sequence. 

Let's take if we use asterisk before the color in the above example.

Tuple Unpacking in Python

color would be created as a list with the first two (or more if present) elements and fruits (str) would be created with the last element. 

We can only have one starred expression in an assignment.

Let's take another example with three variables. 

Tuple unpacking in Python

In this example, 
  • We are using three variables and given asterisk for the middle variable. 
  • First and Last elements in the tuple are assigned to the first and last variables. 
  • All other elements in the middle (from Tuple) are assigned as a list to the starred variable. 

Tuple unpacking would be helpful in many scenarios. We will have a look at how we can use tuple unpacking with dictionaries to unpack key and value from dictionary. 

Dictionary method items would return each key and value combination as a tuple. 

Tuple unpacking with dictionaries in Python

In the above example, for loop is repeated for every item (key and value) of a dictionary and the same would be returned as a tuple. 

Let's use tuple unpacking to unpack key and values.

Tuple unpacking with dictionaries in Python

Key and value are unpacked from tuple and can be used separately inside for loop. 

Hope the above info was useful in understanding Tuple unpacking in Python. 

If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.


Popular posts from this blog

All about READ in RPGLE & Why we use it with SETLL/SETGT?

READ READ is one of the most used Opcodes in RPGLE. As the name suggests main purpose of this Opcode is to read a record from Database file. What are the different READ Opcodes? To list, Below are the five Opcodes.  READ - Read a Record READC - Read Next Changed Record READE - Read Equal Key Record READP - Read Prior Record READPE - Read Prior Equal Record We will see more about each of these later in this article. Before that, We will see a bit about SETLL/SETGT .  SETLL (Set Lower Limit) SETLL accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Corresponding Record (or Next Record if exact match isn't found).  SETGT (Set Greater Than) SETGT accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Next Record (Greater Than the Key value). Syntax: SETLL SEARCH-ARGUMENTS/KEYFIELDS FILENAME SETGT  SEARCH-ARGUMENTS/KEYFIELDS FILENAME One of the below can be passed as Search Arguments. Key Fiel

What we need to know about CHAIN (RPGLE) & How is it different from READ?

CHAIN READ & CHAIN, These are one of the most used (& useful) Opcodes by any RPG developer. These Opcodes are used to read a record from file. So, What's the difference between CHAIN & READ?   CHAIN operation retrieves a record based on the Key specified. It's more like Retrieving Random record from a Database file based on the Key fields.  READ operation reads the record currently pointed to from a Database file. There are multiple Opcodes that start with READ and all are used to read a record but with slight difference. We will see more about different Opcodes and How they are different from each other (and CHAIN) in another article. Few differences to note.  CHAIN requires Key fields to read a record where as READ would read the record currently pointed to (SETLL or SETGT are used to point a Record).  If there are multiple records with the same Key data, CHAIN would return the same record every time. READE can be used to read all the records with the specified Ke

Extract a portion of a Date/Time/Timestamp in RPGLE - IBM i

%SUBDT Extracting Year, Month, Day, Hour, Minutes, Seconds or Milli seconds of a given Date/Time/Timestamp is required most of the times.  This can be extracted easily by using %SUBDT. BIF name looks more similar to %SUBST which is used to extract a portion of string by passing from and two positions of the original string. Instead, We would need to pass a value (i.e., Date, Time or Timestamp ) and Unit (i.e., *YEARS, *MONTHS, *DAYS, *HOURS, *MINUTES, *SECONDS or *MSECONDS) to %SUBDT.  Valid unit should be passed for the type of the value passed. Below are the valid values for each type. Date - *DAYS, *MONTHS, *YEARS Time - *HOURS, *MINUTES, *SECONDS Timestamp - *DAYS, *MONTHS, *YEARS, *HOURS, *MINUTES, *SECONDS, *MSECONDS Syntax: %SUBDT(value : unit { : digits { : decpos} }) Value and Unit are the mandatory arguments.  Digits and Decimal positions are optional and can only be used with *SECONDS for Timestamp. We can either pass the full form for the unit or use the short form. Below i