Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python - unpack tuples, unpacking a tuple.

When we create a tuple, we normally assign values to it. This is called "packing" a tuple:

Packing a tuple:

But, in Python, we are also allowed to extract the values back into variables. This is called "unpacking":

Unpacking a tuple:

Note: The number of variables must match the number of values in the tuple, if not, you must use an asterisk to collect the remaining values as a list.

Advertisement

Using Asterisk *

If the number of variables is less than the number of values, you can add an * to the variable name and the values will be assigned to the variable as a list:

Assign the rest of the values as a list called "red":

If the asterisk is added to another variable name than the last, Python will assign values to the variable until the number of values left matches the number of variables left.

Add a list of values the "tropic" variable:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries
  • Python Tuple Methods
  • Python Tuple - max() Method
  • Python Tuple - min() Method
  • Python Tuple - index() Method
  • Python Tuple - len() Method
  • Python Tuple count() Method
  • Python | Remove empty tuples from a list
  • Python | Reversing a Tuple
  • Python - Clearing a tuple
  • Python - Create a List of Tuples
  • Python | Convert a List into a Tuple
  • Python | Unzip a list of tuples

Unpacking a Tuple in Python

  • tuple() Function in Python
  • Python | Sort a tuple by its float element
  • Python | Accessing nth element from tuples in list

Python Tuples In python tuples are used to store immutable objects. Python Tuples are very similar to lists except to some situations. Python tuples are immutable means that they can not be modified in whole program.

Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called unpacking of a tuple of values into a variable. In packing, we put values into a new tuple while in unpacking we extract those values into a single variable.

Example 1 

NOTE : In unpacking of tuple number of variables on left-hand side should be equal to number of values in given tuple a. Python uses a special syntax to pass optional arguments (*args) for tuple unpacking. This means that there can be many number of arguments in place of (*args) in python. All values will be assigned to every variable on the left-hand side and all remaining values will be assigned to *args .For better understanding consider the following code. 

Example 2 

In python tuples can be unpacked using a function in function tuple is passed and in function values are unpacked into normal variable. Consider the following code for better understanding. 

Example 3 : 

Please Login to comment...

Similar reads.

author

  • python-tuple

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Unpacking in Python: Beyond Parallel Assignment

python unpack tuple assignment

  • Introduction

Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .

Historically, Python developers have generically referred to this kind of operation as tuple unpacking . However, since this Python feature has turned out to be quite useful and popular, it's been generalized to all kinds of iterables. Nowadays, a more modern and accurate term would be iterable unpacking .

In this tutorial, we'll learn what iterable unpacking is and how we can take advantage of this Python feature to make our code more readable, maintainable, and pythonic.

Additionally, we'll also cover some practical examples of how to use the iterable unpacking feature in the context of assignments operations, for loops, function definitions, and function calls.

  • Packing and Unpacking in Python

Python allows a tuple (or list ) of variables to appear on the left side of an assignment operation. Each variable in the tuple can receive one value (or more, if we use the * operator) from an iterable on the right side of the assignment.

For historical reasons, Python developers used to call this tuple unpacking . However, since this feature has been generalized to all kind of iterable, a more accurate term would be iterable unpacking and that's what we'll call it in this tutorial.

Unpacking operations have been quite popular among Python developers because they can make our code more readable, and elegant. Let's take a closer look to unpacking in Python and see how this feature can improve our code.

  • Unpacking Tuples

In Python, we can put a tuple of variables on the left side of an assignment operator ( = ) and a tuple of values on the right side. The values on the right will be automatically assigned to the variables on the left according to their position in the tuple . This is commonly known as tuple unpacking in Python. Check out the following example:

When we put tuples on both sides of an assignment operator, a tuple unpacking operation takes place. The values on the right are assigned to the variables on the left according to their relative position in each tuple . As you can see in the above example, a will be 1 , b will be 2 , and c will be 3 .

To create a tuple object, we don't need to use a pair of parentheses () as delimiters. This also works for tuple unpacking, so the following syntaxes are equivalent:

Since all these variations are valid Python syntax, we can use any of them, depending on the situation. Arguably, the last syntax is more commonly used when it comes to unpacking in Python.

When we are unpacking values into variables using tuple unpacking, the number of variables on the left side tuple must exactly match the number of values on the right side tuple . Otherwise, we'll get a ValueError .

For example, in the following code, we use two variables on the left and three values on the right. This will raise a ValueError telling us that there are too many values to unpack:

Note: The only exception to this is when we use the * operator to pack several values in one variable as we'll see later on.

On the other hand, if we use more variables than values, then we'll get a ValueError but this time the message says that there are not enough values to unpack:

If we use a different number of variables and values in a tuple unpacking operation, then we'll get a ValueError . That's because Python needs to unambiguously know what value goes into what variable, so it can do the assignment accordingly.

  • Unpacking Iterables

The tuple unpacking feature got so popular among Python developers that the syntax was extended to work with any iterable object. The only requirement is that the iterable yields exactly one item per variable in the receiving tuple (or list ).

Check out the following examples of how iterable unpacking works in Python:

When it comes to unpacking in Python, we can use any iterable on the right side of the assignment operator. The left side can be filled with a tuple or with a list of variables. Check out the following example in which we use a tuple on the right side of the assignment statement:

It works the same way if we use the range() iterator:

Even though this is a valid Python syntax, it's not commonly used in real code and maybe a little bit confusing for beginner Python developers.

Finally, we can also use set objects in unpacking operations. However, since sets are unordered collection, the order of the assignments can be sort of incoherent and can lead to subtle bugs. Check out the following example:

If we use sets in unpacking operations, then the final order of the assignments can be quite different from what we want and expect. So, it's best to avoid using sets in unpacking operations unless the order of assignment isn't important to our code.

  • Packing With the * Operator

The * operator is known, in this context, as the tuple (or iterable) unpacking operator . It extends the unpacking functionality to allow us to collect or pack multiple values in a single variable. In the following example, we pack a tuple of values into a single variable by using the * operator:

For this code to work, the left side of the assignment must be a tuple (or a list ). That's why we use a trailing comma. This tuple can contain as many variables as we need. However, it can only contain one starred expression .

We can form a stared expression using the unpacking operator, * , along with a valid Python identifier, just like the *a in the above code. The rest of the variables in the left side tuple are called mandatory variables because they must be filled with concrete values, otherwise, we'll get an error. Here's how this works in practice.

Packing the trailing values in b :

Packing the starting values in a :

Packing one value in a because b and c are mandatory:

Packing no values in a ( a defaults to [] ) because b , c , and d are mandatory:

Supplying no value for a mandatory variable ( e ), so an error occurs:

Packing values in a variable with the * operator can be handy when we need to collect the elements of a generator in a single variable without using the list() function. In the following examples, we use the * operator to pack the elements of a generator expression and a range object to a individual variable:

In these examples, the * operator packs the elements in gen , and ran into g and r respectively. With his syntax, we avoid the need of calling list() to create a list of values from a range object, a generator expression, or a generator function.

Notice that we can't use the unpacking operator, * , to pack multiple values into one variable without adding a trailing comma to the variable on the left side of the assignment. So, the following code won't work:

If we try to use the * operator to pack several values into a single variable, then we need to use the singleton tuple syntax. For example, to make the above example works, we just need to add a comma after the variable r , like in *r, = range(10) .

  • Using Packing and Unpacking in Practice

Packing and unpacking operations can be quite useful in practice. They can make your code clear, readable, and pythonic. Let's take a look at some common use-cases of packing and unpacking in Python.

  • Assigning in Parallel

One of the most common use-cases of unpacking in Python is what we can call parallel assignment . Parallel assignment allows you to assign the values in an iterable to a tuple (or list ) of variables in a single and elegant statement.

For example, let's suppose we have a database about the employees in our company and we need to assign each item in the list to a descriptive variable. If we ignore how iterable unpacking works in Python, we can get ourself writing code like this:

Even though this code works, the index handling can be clumsy, hard to type, and confusing. A cleaner, more readable, and pythonic solution can be coded as follows:

Using unpacking in Python, we can solve the problem of the previous example with a single, straightforward, and elegant statement. This tiny change would make our code easier to read and understand for newcomers developers.

  • Swapping Values Between Variables

Another elegant application of unpacking in Python is swapping values between variables without using a temporary or auxiliary variable. For example, let's suppose we need to swap the values of two variables a and b . To do this, we can stick to the traditional solution and use a temporary variable to store the value to be swapped as follows:

This procedure takes three steps and a new temporary variable. If we use unpacking in Python, then we can achieve the same result in a single and concise step:

In statement a, b = b, a , we're reassigning a to b and b to a in one line of code. This is a lot more readable and straightforward. Also, notice that with this technique, there is no need for a new temporary variable.

  • Collecting Multiple Values With *

When we're working with some algorithms, there may be situations in which we need to split the values of an iterable or a sequence in chunks of values for further processing. The following example shows how to uses a list and slicing operations to do so:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Even though this code works as we expect, dealing with indices and slices can be a little bit annoying, difficult to read, and confusing for beginners. It has also the drawback of making the code rigid and difficult to maintain. In this situation, the iterable unpacking operator, * , and its ability to pack several values in a single variable can be a great tool. Check out this refactoring of the above code:

The line first, *body, last = seq makes the magic here. The iterable unpacking operator, * , collects the elements in the middle of seq in body . This makes our code more readable, maintainable, and flexible. You may be thinking, why more flexible? Well, suppose that seq changes its length in the road and you still need to collect the middle elements in body . In this case, since we're using unpacking in Python, no changes are needed for our code to work. Check out this example:

If we were using sequence slicing instead of iterable unpacking in Python, then we would need to update our indices and slices to correctly catch the new values.

The use of the * operator to pack several values in a single variable can be applied in a variety of configurations, provided that Python can unambiguously determine what element (or elements) to assign to each variable. Take a look at the following examples:

We can move the * operator in the tuple (or list ) of variables to collect the values according to our needs. The only condition is that Python can determine to what variable assign each value.

It's important to note that we can't use more than one stared expression in the assignment If we do so, then we'll get a SyntaxError as follows:

If we use two or more * in an assignment expression, then we'll get a SyntaxError telling us that two-starred expression were found. This is that way because Python can't unambiguously determine what value (or values) we want to assign to each variable.

  • Dropping Unneeded Values With *

Another common use-case of the * operator is to use it with a dummy variable name to drop some useless or unneeded values. Check out the following example:

For a more insightful example of this use-case, suppose we're developing a script that needs to determine the Python version we're using. To do this, we can use the sys.version_info attribute . This attribute returns a tuple containing the five components of the version number: major , minor , micro , releaselevel , and serial . But we just need major , minor , and micro for our script to work, so we can drop the rest. Here's an example:

Now, we have three new variables with the information we need. The rest of the information is stored in the dummy variable _ , which can be ignored by our program. This can make clear to newcomer developers that we don't want to (or need to) use the information stored in _ cause this character has no apparent meaning.

Note: By default, the underscore character _ is used by the Python interpreter to store the resulting value of the statements we run in an interactive session. So, in this context, the use of this character to identify dummy variables can be ambiguous.

  • Returning Tuples in Functions

Python functions can return several values separated by commas. Since we can define tuple objects without using parentheses, this kind of operation can be interpreted as returning a tuple of values. If we code a function that returns multiple values, then we can perform iterable packing and unpacking operations with the returned values.

Check out the following example in which we define a function to calculate the square and cube of a given number:

If we define a function that returns comma-separated values, then we can do any packing or unpacking operation on these values.

  • Merging Iterables With the * Operator

Another interesting use-case for the unpacking operator, * , is the ability to merge several iterables into a final sequence. This functionality works for lists, tuples, and sets. Take a look at the following examples:

We can use the iterable unpacking operator, * , when defining sequences to unpack the elements of a subsequence (or iterable) into the final sequence. This will allow us to create sequences on the fly from other existing sequences without calling methods like append() , insert() , and so on.

The last two examples show that this is also a more readable and efficient way to concatenate iterables. Instead of writing list(my_set) + my_list + list(my_tuple) + list(range(1, 4)) + list(my_str) we just write [*my_set, *my_list, *my_tuple, *range(1, 4), *my_str] .

  • Unpacking Dictionaries With the ** Operator

In the context of unpacking in Python, the ** operator is called the dictionary unpacking operator . The use of this operator was extended by PEP 448 . Now, we can use it in function calls, in comprehensions and generator expressions, and in displays .

A basic use-case for the dictionary unpacking operator is to merge multiple dictionaries into one final dictionary with a single expression. Let's see how this works:

If we use the dictionary unpacking operator inside a dictionary display, then we can unpack dictionaries and combine them to create a final dictionary that includes the key-value pairs of the original dictionaries, just like we did in the above code.

An important point to note is that, if the dictionaries we're trying to merge have repeated or common keys, then the values of the right-most dictionary will override the values of the left-most dictionary. Here's an example:

Since the a key is present in both dictionaries, the value that prevail comes from vowels , which is the right-most dictionary. This happens because Python starts adding the key-value pairs from left to right. If, in the process, Python finds keys that already exit, then the interpreter updates that keys with the new value. That's why the value of the a key is lowercased in the above example.

  • Unpacking in For-Loops

We can also use iterable unpacking in the context of for loops. When we run a for loop, the loop assigns one item of its iterable to the target variable in every iteration. If the item to be assigned is an iterable, then we can use a tuple of target variables. The loop will unpack the iterable at hand into the tuple of target variables.

As an example, let's suppose we have a file containing data about the sales of a company as follows:

From this table, we can build a list of two-elements tuples. Each tuple will contain the name of the product, the price, and the sold units. With this information, we want to calculate the income of each product. To do this, we can use a for loop like this:

This code works as expected. However, we're using indices to get access to individual elements of each tuple . This can be difficult to read and to understand by newcomer developers.

Let's take a look at an alternative implementation using unpacking in Python:

We're now using iterable unpacking in our for loop. This makes our code way more readable and maintainable because we're using descriptive names to identify the elements of each tuple . This tiny change will allow a newcomer developer to quickly understand the logic behind the code.

It's also possible to use the * operator in a for loop to pack several items in a single target variable:

In this for loop, we're catching the first element of each sequence in first . Then the * operator catches a list of values in its target variable rest .

Finally, the structure of the target variables must agree with the structure of the iterable. Otherwise, we'll get an error. Take a look at the following example:

In the first loop, the structure of the target variables, (a, b), c , agrees with the structure of the items in the iterable, ((1, 2), 2) . In this case, the loop works as expected. In contrast, the second loop uses a structure of target variables that don't agree with the structure of the items in the iterable, so the loop fails and raises a ValueError .

  • Packing and Unpacking in Functions

We can also use Python's packing and unpacking features when defining and calling functions. This is a quite useful and popular use-case of packing and unpacking in Python.

In this section, we'll cover the basics of how to use packing and unpacking in Python functions either in the function definition or in the function call.

Note: For a more insightful and detailed material on these topics, check out Variable-Length Arguments in Python with *args and **kwargs .

  • Defining Functions With * and **

We can use the * and ** operators in the signature of Python functions. This will allow us to call the function with a variable number of positional arguments ( * ) or with a variable number of keyword arguments, or both. Let's consider the following function:

The above function requires at least one argument called required . It can accept a variable number of positional and keyword arguments as well. In this case, the * operator collects or packs extra positional arguments in a tuple called args and the ** operator collects or packs extra keyword arguments in a dictionary called kwargs . Both, args and kwargs , are optional and automatically default to () and {} respectively.

Even though the names args and kwargs are widely used by the Python community, they're not a requirement for these techniques to work. The syntax just requires * or ** followed by a valid identifier. So, if you can give meaningful names to these arguments, then do it. That will certainly improve your code's readability.

  • Calling Functions With * and **

When calling functions, we can also benefit from the use of the * and ** operator to unpack collections of arguments into separate positional or keyword arguments respectively. This is the inverse of using * and ** in the signature of a function. In the signature, the operators mean collect or pack a variable number of arguments in one identifier. In the call, they mean unpack an iterable into several arguments.

Here's a basic example of how this works:

Here, the * operator unpacks sequences like ["Welcome", "to"] into positional arguments. Similarly, the ** operator unpacks dictionaries into arguments whose names match the keys of the unpacked dictionary.

We can also combine this technique and the one covered in the previous section to write quite flexible functions. Here's an example:

The use of the * and ** operators, when defining and calling Python functions, will give them extra capabilities and make them more flexible and powerful.

Iterable unpacking turns out to be a pretty useful and popular feature in Python. This feature allows us to unpack an iterable into several variables. On the other hand, packing consists of catching several values into one variable using the unpacking operator, * .

In this tutorial, we've learned how to use iterable unpacking in Python to write more readable, maintainable, and pythonic code.

With this knowledge, we are now able to use iterable unpacking in Python to solve common problems like parallel assignment and swapping values between variables. We're also able to use this Python feature in other structures like for loops, function calls, and function definitions.

You might also like...

  • Hidden Features of Python
  • Python Docstrings
  • Handling Unix Signals in Python
  • The Best Machine Learning Libraries in Python
  • Guide to Sending HTTP Requests in Python with urllib3

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Leodanis is an industrial engineer who loves Python and software development. He is a self-taught Python programmer with 5+ years of experience building desktop applications with PyQt.

In this article

python unpack tuple assignment

Building Your First Convolutional Neural Network With Keras

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup

Data Visualization in Python with Matplotlib and Pandas

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

© 2013- 2024 Stack Abuse. All rights reserved.

Home » Python Basics » Python Unpacking Tuple

Python Unpacking Tuple

Summary : in this tutorial, you’ll learn how to unpack tuples in Python.

Reviewing Python tuples

Python defines a tuple using commas ( , ), not parentheses () . For example, the following defines a tuple with two elements:

Python uses the parentheses to make the tuple clearer:

Python also uses the parentheses to create an empty tuple:

In addition, you can use the tuple() constructor like this:

To define a tuple with only one element, you still need to use a comma. The following example illustrates how to define a tuple with one element:

It’s equivalent to the following:

Note that the following is an integer , not a tuple:

Unpacking a tuple

Unpacking a tuple means splitting the tuple’s elements into individual variables . For example:

The left side:

is a tuple of two variables x and y .

The right side is also a tuple of two integers 1 and 2 .

The expression assigns the tuple elements on the right side (1, 2) to each variable on the left side (x, y) based on the relative position of each element.

In the above example, x will take 1 and y will take 2 .

See another example:

The right side is a tuple of three integers 10 , 20 , and 30 . You can quickly check its type as follows:

In the above example, the x , y , and z variables will take the values 10 , 20 , and 30 respectively.

Using unpacking tuple to swap values of two variables

Traditionally, to swap the values of two variables, you would use a temporary variable like this:

In Python, you can use the unpacking tuple syntax to achieve the same result:

The following expression swaps the values of two variables, x and y.

In this expression, Python evaluates the right-hand side first and then assigns the variable from the left-hand side to the values from the right-hand side.

ValueError: too many values to unpack

The following example unpacks the elements of a tuple into variables. However, it’ll result in an error:

This error is because the right-hand side returns three values while the left-hand side only has two variables.

To fix this, you can add a _ variable:

The _ variable is a regular variable in Python. By convention, it’s called a dummy variable.

Typically, you use the dummy variable to unpack when you don’t care and use its value afterward.

Extended unpacking using the * operator

Sometimes, you don’t want to unpack every single item in a tuple. For example, you may want to unpack the first and second elements. In this case, you can use the * operator. For example:

In this example, Python assigns 192 to r , 210 to g . Also, Python packs the remaining elements 100 and 0.5 into a list and assigns it to the other variable.

Notice that you can only use the * operator once on the left-hand side of an unpacking assignment.

The following example results in error:

Using the * operator on the right hand side

Python allows you to use the * operator on the right-hand side. Suppose that you have two tuples:

The following example uses the * operator to unpack those tuples and merge them into a single tuple:

  • Python uses the commas ( , ) to define a tuple, not parentheses.
  • Unpacking tuples means assigning individual elements of a tuple to multiple variables.
  • Use the * operator to assign remaining elements of an unpacking assignment into a list and assign it to a variable.

Unpack a tuple and list in Python

In Python, you can assign elements of a tuple or list to multiple variables. It is called sequence unpacking.

  • 5. Data Structures - Tuples and Sequences — Python 3.11.3 documentation

Basics of unpacking a tuple and a list

Unpack a nested tuple and list, unpack with _ (underscore), unpack with * (asterisk).

See the following article for information on unpacking lists, tuples, and dictionaries ( dict ) as arguments in a function using * (asterisk).

  • Expand and pass a list and dictionary as arguments in Python

By separating variables with commas ( , ) on the left side, you can assign elements of a tuple or list on the right side to each corresponding variable. The following examples use tuples, but the same approach applies to lists.

Since the parentheses of a tuple can be omitted, multiple values can be assigned to multiple variables in a single line, as shown below.

  • Multiple assignment in Python: Assign multiple values or the same value to multiple variables

An error occurs if the number of variables and elements does not match.

If there are fewer variables than elements, you can prefix the variable name with an asterisk * to assign the remaining elements as a list. This is described later.

You can also unpack a nested tuple or list. If you want to unpack the inner elements, enclose the variable with () or [] .

By convention, in Python, unnecessary values may be assigned to _ (underscore). It does not have any special syntactic meaning but is simply a variable named _ .

When there are fewer variables than elements, prefixing the variable name with an asterisk * groups the remaining elements as a list.

It is implemented in Python 3 and cannot be used in Python 2.

The elements from the beginning and the end are assigned to variables without * , and the remaining elements are assigned as a list to variables prefixed with * .

For example, to assign only the first two elements of a tuple or a list to variables, use the underscore _ for the remaining elements.

The same operation can be written as follows.

You can prefix only one variable with * . If multiple variables are prefixed with * , the assignment of elements becomes ambiguous, resulting in a SyntaxError .

Note that if only one element is assigned to a variable prefixed with * , it will still be assigned as a list.

If there are no extra elements, an empty list is assigned.

Related Categories

Related articles.

  • Sort a list, string, tuple in Python (sort, sorted)
  • Shuffle a list, string, tuple in Python (random.shuffle, sample)
  • How to use deque in Python (collections.deque)
  • Initialize a list of any size with specific values in Python
  • Convert between NumPy array and Python list
  • Convert 1D array to 2D array in Python (numpy.ndarray, list)
  • Compare lists in Python
  • GROUP BY in Python (itertools.groupby)
  • Extract and replace elements that meet the conditions of a list of strings in Python
  • Sort a 2D list in Python
  • Get the n-largest/smallest elements from a list in Python
  • Filter (extract/remove) items of a list with filter() in Python
  • Use enumerate() and zip() together in Python
  • Sort a list of dictionaries by the value of the specific key in Python
  • Transpose 2D list in Python (swap rows and columns)
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

PythonForBeginners.com

PythonForBeginners.com

Learn By Example

Tuple Unpacking in Python

Author: Aditya Raj Last Updated: July 12, 2023

Python provides us with different shorthand methods to perform various tasks. In this article, we will discuss tuple unpacking in Python with examples.

What is Unpacking in Python?

Tuple unpacking using parallel assignment, tuple unpacking using the * operator, unpack tuple into a list in python, unpack tuple into a set.

In Python, the unpacking operation is used to assign elements of a collection object like a list, tuple, dictionary, etc directly to different variables. We use the Python unpacking operator and parallel assignment to unpack collection objects. 

Let us discuss both ways for tuple unpacking in Python.

python unpack tuple assignment

If a tuple has N elements, we can perform tuple unpacking in Python using parallel assignment as shown in the following syntax.

In the above syntax, the number of variables on the left-hand side of the assignment operator must be equal to the number of elements in the tuple on the right side of the assignment operator. 

After tuple unpacking, the elements in the tuple are assigned to the variables at the corresponding position on the left-hand side of the assignment operator.  The first element of the tuple is assigned to the first variable, the second element of the tuple is assigned to the second variable on LHS, and so on. You can observe this in the following example.

In the above example, we have defined a tuple with four elements. Then, we unpack the tuple using the parallel assignment. You can observe that the elements in the tuple are assigned to the variable at the same position on the left-hand side of the assignment operator. 

In the parallel assignment operation, if the number of variables is less than the elements in the tuple, the program runs into a Python ValueError exception. You can observe this in the following example.

In the above code, you can observe that the tuple contains six elements whereas there are only four variables on the left side of the assignment operator during tuple unpacking. Hence, the program runs into a ValueError exception.

In a similar manner, if the number of variables exceeds the number of elements in the tuple, the program runs into a ValueError exception saying that there aren’t enough values to unpack. You can observe this in the following example.

Here, we have only four elements in the tuple. However, the assignment statement contains six variables. Due to this, the program runs into a ValueError exception.

If we have fewer variables than the number of elements in the tuple, we can use the * operator for tuple unpacking in Python. For tuple unpacking using the * operator, we will use the following syntax

Here, if the tuple myTuple contains more than N variables, the first N elements of the tuple are assigned to variables var1, var2,.. till varN. The rest of the elements are stored in the variable var as a list. You can observe this in the following example.

In the above example, there are nine elements in the tuple. On the contrary, we have only four variables. You can observe that the fourth variable d in the code uses the * operator. Hence, first three elements of the tuple are assigned to the variables a, b, and c. The rest of the elements are packed in a list and assigned to the variable d.

Instead of the above approach, you can also use the following syntax for tuple unpacking in Python.

When we use the above syntax, the last N elements of the tuple myTuple are assigned to the variables var1, var2, till varN. The remaining elements of the tuple from starting index are stored in the variable var as a list. You can observe this in the following example.

In the above example, the first variable in the assignment statement uses the * operator. Hence, the last three elements of the tuple are assigned to variables b, c, and d. Rest of the elements are packed into a list and assigned to the variable a.

You can also choose to put the variable containing the * operator in the middle of the variables on the left-hand side of the assignment operator. For instance, consider the following syntax.

If we use the above syntax, the first M elements of myTuple are assigned to the variables var1, var2, till varM. The last N-M elements are assigned to the variables varM+1, varM+2,… till varN. The rest of the elements in the middle of the tuple are assigned to the variable var in a list. You can observe this in the following example.

In this example, we have used the * operator with the third variable in the assignment statement. Hence, the first two elements of the tuple are assigned to variables a, and b. The last element of the tuple is assigned to the variable d. Rest of the elements are assigned in a list to the variable c.

You can also use the tuple unpacking operation to create a list directly from a tuple. For this, we will use the following syntax.

After executing the above statement, we get a list myList containing elements from the tuple myTuple.

Similar to a list, we can also create a set from a tuple using the unpacking operator in Python as shown below.

In this article, we discussed the basics of tuple unpacking in Python. To learn more about tuples, you can read this article on tuple comprehension . You might also like this article on tuple vs list in Python . 

I hope you enjoyed reading this article. Stay tuned for more informative articles. 

Happy Learning!

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

More Python Topics

Tuple Unpacking

Tuple unpacking (aka "multiple assignment" or "iterable unpacking") is often underutilized by new Python programmers. It's tempting to reach for indexes when working with tuples, lists, and other sequences. But if we know the size/shape of the tuple (or other sequence ) we're working with, we can unpack it using

Tuple unpacking screencasts/articles

  • Tuple unpacking
  • Deep tuple unpacking
  • Tuple unpacking isn't just for tuples
  • Extended iterable unpacking

Recommended Resources

  • Article: Multiple assignment and tuple unpacking improve Python code readability by Trey Hunner

A Python tip every week

Need to fill-in gaps in your Python skills?

Sign up for my Python newsletter where I share one of my favorite Python tips every week .

Need to fill-in gaps in your Python skills ? I send weekly emails designed to do just that.

python unpack tuple assignment

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • 13.1 Introduction
  • 13.2 Tuple Packing
  • 13.3 Tuple Assignment with Unpacking
  • 13.4 Tuples as Return Values
  • 13.5 Unpacking Tuples as Arguments to Function Calls
  • 13.6 Glossary
  • 13.7 Exercises
  • 13.8 Chapter Assessment
  • 13.2. Tuple Packing" data-toggle="tooltip">
  • 13.4. Tuples as Return Values' data-toggle="tooltip" >

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

13.3. Tuple Assignment with Unpacking ¶

Python has a very powerful tuple assignment feature that allows a tuple of variable names on the left of an assignment statement to be assigned values from a tuple on the right of the assignment. Another way to think of this is that the tuple of values is unpacked into the variable names.

This does the equivalent of seven assignment statements, all on one easy line.

Naturally, the number of variables on the left and the number of values on the right have to be the same.

Unpacking into multiple variable names also works with lists, or any other sequence type, as long as there is exactly one value for each variable. For example, you can write x, y = [3, 4] .

13.3.1. Swapping Values between Variables ¶

This feature is used to enable swapping the values of two variables. With conventional assignment statements, we have to use a temporary variable. For example, to swap a and b :

Tuple assignment solves this problem neatly:

The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments. This feature makes tuple assignment quite versatile.

13.3.2. Unpacking Into Iterator Variables ¶

Multiple assignment with unpacking is particularly useful when you iterate through a list of tuples. You can unpack each tuple into several loop variables. For example:

On the first iteration the tuple ('Paul', 'Resnick') is unpacked into the two variables first_name and last_name . One the second iteration, the next tuple is unpacked into those same loop variables.

13.3.3. The Pythonic Way to Enumerate Items in a Sequence ¶

When we first introduced the for loop, we provided an example of how to iterate through the indexes of a sequence, and thus enumerate the items and their positions in the sequence.

We are now prepared to understand a more pythonic approach to enumerating items in a sequence. Python provides a built-in function enumerate . It takes a sequence as input and returns a sequence of tuples. In each tuple, the first element is an integer and the second is an item from the original sequence. (It actually produces an “iterable” rather than a list, but we can use it in a for loop as the sequence to iterate over.)

The pythonic way to consume the results of enumerate, however, is to unpack the tuples while iterating through them, so that the code is easier to understand.

Check your Understanding

Consider the following alternative way to swap the values of variables x and y. What’s wrong with it?

  • You can't use different variable names on the left and right side of an assignment statement.
  • Sure you can; you can use any variable on the right-hand side that already has a value.
  • At the end, x still has it's original value instead of y's original value.
  • Once you assign x's value to y, y's original value is gone.
  • Actually, it works just fine!

With only one line of code, assign the variables water , fire , electric , and grass to the values “Squirtle”, “Charmander”, “Pikachu”, and “Bulbasaur”

With only one line of code, assign four variables, v1 , v2 , v3 , and v4 , to the following four values: 1, 2, 3, 4.

If you remember, the .items() dictionary method produces a sequence of tuples. Keeping this in mind, we have provided you a dictionary called pokemon . For every key value pair, append the key to the list p_names , and append the value to the list p_number . Do not use the .keys() or .values() methods.

The .items() method produces a sequence of key-value pair tuples. With this in mind, write code to create a list of keys from the dictionary track_medal_counts and assign the list to the variable name track_events . Do NOT use the .keys() method.

Guru99

Python TUPLE – Pack, Unpack, Compare, Slicing, Delete, Key

Steve Campbell

What is Tuple Matching in Python?

Tuple Matching in Python is a method of grouping the tuples by matching the second element in the tuples. It is achieved by using a dictionary by checking the second element in each tuple in python programming. However, we can make new tuples by taking portions of existing tuples.

Tuple Syntax

To write an empty tuple, you need to write as two parentheses containing nothing-

For writing tuple for a single value, you need to include a comma, even though there is a single value. Also at the end you need to write semicolon as shown below.

Tuple indices begin at 0, and they can be concatenated, sliced and so on.

Tuple Assignment

Python has tuple assignment feature which enables you to assign more than one variable at a time. In here, we have assigned tuple 1 with the persons information like name, surname, birth year, etc. and another tuple 2 with the values in it like number (1,2,3,….,7).

For Example,

(name, surname, birth year, favorite movie and year, profession, birthplace) = Robert

Here is the code,

  • Tuple 1 includes list of information of Robert
  • Tuple 2 includes list of numbers in it
  • We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4
  • Run the code- It gives name Robert for first tuple while for second tuple it gives number (2,3 and 4)

Packing and Unpacking

  • In packing, we place value into a new tuple while in unpacking we extract those values back into variables.

Comparing tuples

  • A comparison operator in Python can work with tuples.

The comparison starts with a first element of each tuple. If they do not compare to =,< or > then it proceed to the second element and so on.

It starts with comparing the first element from each of the tuples

Let’s study this with an example-

Case1: Comparison starts with a first element of each tuple. In this case 5>1, so the output a is bigger

Case 2: Comparison starts with a first element of each tuple. In this case 5>5 which is inconclusive. So it proceeds to the next element. 6>4, so the output a is bigger

Case 3: Comparison starts with a first element of each tuple. In this case 5>6 which is false. So it goes into the else block and prints “b is bigger.”

  • Using tuples as keys in dictionaries

Since tuples are hashable, and list is not, we must use tuple as the key if we need to create a composite key to use in a dictionary.

Example : We would come across a composite key if we need to create a telephone directory that maps, first-name, last-name, pairs of telephone numbers, etc. Assuming that we have declared the variables as last and first number, we could write a dictionary assignment statement as shown below:

Inside the brackets, the expression is a tuple. We could use tuple assignment in a for loop to navigate this dictionary.

This loop navigates the keys in the directory, which are tuples. It assigns the elements of each tuple to last and first and then prints the name and corresponding telephone number.

Tuples and dictionary

Dictionary can return the list of tuples by calling items, where each tuple is a key value pair.

Deleting Tuples

Tuples are immutable and cannot be deleted. You cannot delete or remove items from a tuple. But deleting tuple entirely is possible by using the keyword

Slicing of Tuple

To fetch specific sets of sub-elements from tuple or list, we use this unique function called slicing. Slicing is not only applicable to tuple but also for array and list.

The output of this code will be (‘c’, ‘d’).

Here is the Python 2 Code for all above example

Built-in functions with Tuple

To perform different task, tuple allows you to use many built-in functions like all(), any(), enumerate(), max(), min(), sorted(), len(), tuple(), etc.

Advantages of tuple over list

  • Iterating through tuple is faster than with list, since tuples are immutable.
  • Tuples that consist of immutable elements can be used as key for dictionary, which is not possible with list
  • If you have data that is immutable, implementing it as tuple will guarantee that it remains write-protected

Python has tuple assignment feature which enables you to assign more than one variable at a time.

  • Packing and Unpacking of Tuples
  • Tuples are hashable, and list are not
  • We must use tuple as the key if we need to create a composite key to use in a dictionary
  • Dictionary can return the list of tuples by calling items, where each tuple is a key value pair
  • Tuples are immutable and cannot be deleted. You cannot delete or remove items from a tuple. But deleting tuple entirely is possible by using the keyword “del”
  • To fetch specific sets of sub-elements from tuple or list, we use this unique function called slicing
  • Online Python Compiler (Editor / Interpreter / IDE) to Run Code
  • PyUnit Tutorial: Python Unit Testing Framework (with Example)
  • How to Install Python on Windows [Pycharm IDE]
  • Hello World: Create your First Python Program
  • Python Variables: How to Define/Declare String Variable Types
  • Python Strings: Replace, Join, Split, Reverse, Uppercase & Lowercase
  • Dictionary in Python with Syntax & Example
  • Operators in Python – Logical, Arithmetic, Comparison

Trey Hunner

I help developers level-up their python skills, multiple assignment and tuple unpacking improve python code readability.

Mar 7 th , 2018 4:30 pm | Comments

Whether I’m teaching new Pythonistas or long-time Python programmers, I frequently find that Python programmers underutilize multiple assignment .

Multiple assignment (also known as tuple unpacking or iterable unpacking) allows you to assign multiple variables at the same time in one line of code. This feature often seems simple after you’ve learned about it, but it can be tricky to recall multiple assignment when you need it most .

In this article we’ll see what multiple assignment is, we’ll take a look at common uses of multiple assignment, and then we’ll look at a few uses for multiple assignment that are often overlooked.

Note that in this article I will be using f-strings which are a Python 3.6+ feature. If you’re on an older version of Python, you’ll need to mentally translate those to use the string format method.

How multiple assignment works

I’ll be using the words multiple assignment , tuple unpacking , and iterable unpacking interchangeably in this article. They’re all just different words for the same thing.

Python’s multiple assignment looks like this:

Here we’re setting x to 10 and y to 20 .

What’s happening at a lower level is that we’re creating a tuple of 10, 20 and then looping over that tuple and taking each of the two items we get from looping and assigning them to x and y in order.

This syntax might make that a bit more clear:

Parenthesis are optional around tuples in Python and they’re also optional in multiple assignment (which uses a tuple-like syntax). All of these are equivalent:

Multiple assignment is often called “tuple unpacking” because it’s frequently used with tuples. But we can use multiple assignment with any iterable, not just tuples. Here we’re using it with a list:

And with a string:

Anything that can be looped over can be “unpacked” with tuple unpacking / multiple assignment.

Here’s another example to demonstrate that multiple assignment works with any number of items and that it works with variables as well as objects we’ve just created:

Note that on that last line we’re actually swapping variable names, which is something multiple assignment allows us to do easily.

Alright, let’s talk about how multiple assignment can be used.

Unpacking in a for loop

You’ll commonly see multiple assignment used in for loops.

Let’s take a dictionary:

Instead of looping over our dictionary like this:

You’ll often see Python programmers use multiple assignment by writing this:

When you write the for X in Y line of a for loop, you’re telling Python that it should do an assignment to X for each iteration of your loop. Just like in an assignment using the = operator, we can use multiple assignment here.

Is essentially the same as this:

We’re just not doing an unnecessary extra assignment in the first example.

So multiple assignment is great for unpacking dictionary items into key-value pairs, but it’s helpful in many other places too.

It’s great when paired with the built-in enumerate function:

And the zip function:

If you’re unfamiliar with enumerate or zip , see my article on looping with indexes in Python .

Newer Pythonistas often see multiple assignment in the context of for loops and sometimes assume it’s tied to loops. Multiple assignment works for any assignment though, not just loop assignments.

An alternative to hard coded indexes

It’s not uncommon to see hard coded indexes (e.g. point[0] , items[1] , vals[-1] ) in code:

When you see Python code that uses hard coded indexes there’s often a way to use multiple assignment to make your code more readable .

Here’s some code that has three hard coded indexes:

We can make this code much more readable by using multiple assignment to assign separate month, day, and year variables:

Whenever you see hard coded indexes in your code, stop to consider whether you could use multiple assignment to make your code more readable.

Multiple assignment is very strict

Multiple assignment is actually fairly strict when it comes to unpacking the iterable we give to it.

If we try to unpack a larger iterable into a smaller number of variables, we’ll get an error:

If we try to unpack a smaller iterable into a larger number of variables, we’ll also get an error:

This strictness is pretty great. If we’re working with an item that has a different size than we expected, the multiple assignment will fail loudly and we’ll hopefully now know about a bug in our program that we weren’t yet aware of.

Let’s look at an example. Imagine that we have a short command line program that parses command-line arguments in a rudimentary way, like this:

Our program is supposed to accept 2 arguments, like this:

But if someone called our program with three arguments, they will not see an error:

There’s no error because we’re not validating that we’ve received exactly 2 arguments.

If we use multiple assignment instead of hard coded indexes, the assignment will verify that we receive exactly the expected number of arguments:

Note : we’re using the variable name _ to note that we don’t care about sys.argv[0] (the name of our program). Using _ for variables you don’t care about is just a convention.

An alternative to slicing

So multiple assignment can be used for avoiding hard coded indexes and it can be used to ensure we’re strict about the size of the tuples/iterables we’re working with.

Multiple assignment can be used to replace hard coded slices too!

Slicing is a handy way to grab a specific portion of the items in lists and other sequences.

Here are some slices that are “hard coded” in that they only use numeric indexes:

Whenever you see slices that don’t use any variables in their slice indexes, you can often use multiple assignment instead. To do this we have to talk about a feature that I haven’t mentioned yet: the * operator.

In Python 3.0, the * operator was added to the multiple assignment syntax, allowing us to capture remaining items after an unpacking into a list:

The * operator allows us to replace hard coded slices near the ends of sequences.

These two lines are equivalent:

These two lines are equivalent also:

With the * operator and multiple assignment you can replace things like this:

With more descriptive code, like this:

So if you see hard coded slice indexes in your code, consider whether you could use multiple assignment to clarify what those slices really represent.

Deep unpacking

This next feature is something that long-time Python programmers often overlook. It doesn’t come up quite as often as the other uses for multiple assignment that I’ve discussed, but it can be very handy to know about when you do need it.

We’ve seen multiple assignment for unpacking tuples and other iterables. We haven’t yet seen that this is can be done deeply .

I’d say that the following multiple assignment is shallow because it unpacks one level deep:

And I’d say that this multiple assignment is deep because it unpacks the previous point tuple further into x , y , and z variables:

If it seems confusing what’s going on above, maybe using parenthesis consistently on both sides of this assignment will help clarify things:

We’re unpacking one level deep to get two objects, but then we take the second object and unpack it also to get 3 more objects. Then we assign our first object and our thrice-unpacked second object to our new variables ( color , x , y , and z ).

Take these two lists:

Here’s an example of code that works with these lists by using shallow unpacking:

And here’s the same thing with deeper unpacking:

Note that in this second case, it’s much more clear what type of objects we’re working with. The deep unpacking makes it apparent that we’re receiving two 2-itemed tuples each time we loop.

Deep unpacking often comes up when nesting looping utilities that each provide multiple items. For example, you may see deep multiple assignments when using enumerate and zip together:

I said before that multiple assignment is strict about the size of our iterables as we unpack them. With deep unpacking we can also be strict about the shape of our iterables .

This works:

But this buggy code works too:

Whereas this works:

But this does not:

With multiple assignment we’re assigning variables while also making particular assertions about the size and shape of our iterables. Multiple assignment will help you clarify your code to both humans (for better code readability ) and to computers (for improved code correctness ).

Using a list-like syntax

I noted before that multiple assignment uses a tuple-like syntax, but it works on any iterable. That tuple-like syntax is the reason it’s commonly called “tuple unpacking” even though it might be more clear to say “iterable unpacking”.

I didn’t mention before that multiple assignment also works with a list-like syntax .

Here’s a multiple assignment with a list-like syntax:

This might seem really strange. What’s the point of allowing both list-like and tuple-like syntaxes?

I use this feature rarely, but I find it helpful for code clarity in specific circumstances.

Let’s say I have code that used to look like this:

And our well-intentioned coworker has decided to use deep multiple assignment to refactor our code to this:

See that trailing comma on the left-hand side of the assignment? It’s easy to miss and it makes this code look sort of weird. What is that comma even doing in this code?

That trailing comma is there to make a single item tuple. We’re doing deep unpacking here.

Here’s another way we could write the same code:

This might make that deep unpacking a little more obvious but I’d prefer to see this instead:

The list-syntax in our assignment makes it more clear that we’re unpacking a one-item iterable and then unpacking that single item into value and times_seen variables.

When I see this, I also think I bet we’re unpacking a single-item list . And that is in fact what we’re doing. We’re using a Counter object from the collections module here. The most_common method on Counter objects allows us to limit the length of the list returned to us. We’re limiting the list we’re getting back to just a single item.

When you’re unpacking structures that often hold lots of values (like lists) and structures that often hold a very specific number of values (like tuples) you may decide that your code appears more semantically accurate if you use a list-like syntax when unpacking those list-like structures.

If you’d like you might even decide to adopt a convention of always using a list-like syntax when unpacking list-like structures (frequently the case when using * in multiple assignment):

I don’t usually use this convention myself, mostly because I’m just not in the habit of using it. But if you find it helpful, you might consider using this convention in your own code.

When using multiple assignment in your code, consider when and where a list-like syntax might make your code more descriptive and more clear. This can sometimes improve readability.

Don’t forget about multiple assignment

Multiple assignment can improve both the readability of your code and the correctness of your code. It can make your code more descriptive while also making implicit assertions about the size and shape of the iterables you’re unpacking.

The use for multiple assignment that I often see forgotten is its ability to replace hard coded indexes , including replacing hard coded slices (using the * syntax). It’s also common to overlook the fact that multiple assignment works deeply and can be used with both a tuple-like syntax and a list-like syntax.

It’s tricky to recognize and remember all the cases that multiple assignment can come in handy. Please feel free to use this article as your personal reference guide to multiple assignment.

Get practice with multiple assignment

You don’t learn by reading articles like this one, you learn by writing code .

To get practice writing some readable code using tuple unpacking, sign up for Python Morsels using the form below. If you sign up to Python Morsels using this form, I’ll immediately send you an exercise that involves tuple unpacking.

Intro to Python courses often skip over some fundamental Python concepts .

Sign up below and I'll share ideas new Pythonistas often overlook .

You're nearly signed up. You just need to check your email and click the link there to set your password .

Right after you've set your password you'll receive your first Python Morsels exercise.

Python Tuple Unpacking: 2 Quick Methods for Unpacking Tuples

Python (1)

This Article is going to clarify different ways to unpack a Tuple, following certain examples on our code snippet. Let’s get into it without wasting time.

Before getting started, First of all, Let’s understand what a Tuple is in python .

A tuple is one of the four popular in-built collections in Python among List, Set, and Dictionary. It is used to store ordered, indexed collection of data irrespective of datatypes.

Similar to Arrays, the first value in the Tuple will have the index [0], the second value [1], and so on. A Tuple can be created by following commands.

Our new_tuple will be created as follows.

Sample Tuple

Some key features of a Tuple in Python are as follows.

  • It’s immutable in nature. Once a Tuple is created, it is neither possible to modify its elements nor to delete.
  • Deleting an element from a Tuple is not possible. But deleting a Tuple is.
  • Tuples can store duplicate values .
  • We can create an empty Tuple.
  • We can create a Tuple with a single element.
  • Concatenation is possible in between two or more Tuples.
  • Tuples do not support resizing methods:  append(),   remove() ,  pop()  etc.

As you know A Tuple is immutable in nature. Its values or contents can not be changed once created. But one thing we can do is, We can unpack the contents of a Tuple. Unpacking a Tuple means splitting the Tuple’s contents into individual variables. We are going to learn here three methods to do the same followed by some examples. Let’s understand them as well.

Unpacking a Python Tuple By Reassigning

In the above example, We assigned each content of the Tuple to individual variables. Let’s see the contents of each variable by following the code snippet.

While using this method, We must remember that We need to take the no. of variables the same as the no. of contents inside the Tuple. otherwise, it will throw errors as follows.

Error( Two Many Values to Unpack )

Unpacking a Tuple Using the Asterisk * sign

In this example, We are going to use the Asterisk (*) operator. If the number of variables is less than the number of contents inside our Tuple, We can add a  *  to the variable name and the values will be assigned to the variable as a list. Let’s try this as the following code snippet.

Now, We can see the result by printing the variables individually.

We can see that the four contents in between created a list and assigned to y. In this way, This method works. We can understand better by following the below examples in our code snippet.

Note: While using this method, add the * operator to a single variable only. Else, it will throw an error as follow.

Multisigned Error

In this article, We covered how to unpack a Tuple in Python. Tuples are of advantage when used for the use case it is designed for like other elements in Python. Hope You must have enjoyed it. We must visit again with some more exciting topics.

  • Tuple Assignment

Introduction

Tuples are basically a data type in python . These tuples are an ordered collection of elements of different data types. Furthermore, we represent them by writing the elements inside the parenthesis separated by commas. We can also define tuples as lists that we cannot change. Therefore, we can call them immutable tuples. Moreover, we access elements by using the index starting from zero. We can create a tuple in various ways. Here, we will study tuple assignment which is a very useful feature in python.

In python, we can perform tuple assignment which is a quite useful feature. We can initialise or create a tuple in various ways. Besides tuple assignment is a special feature in python. We also call this feature unpacking of tuple.

The process of assigning values to a tuple is known as packing. While on the other hand, the unpacking or tuple assignment is the process that assigns the values on the right-hand side to the left-hand side variables. In unpacking, we basically extract the values of the tuple into a single variable.

Moreover, while performing tuple assignments we should keep in mind that the number of variables on the left-hand side and the number of values on the right-hand side should be equal. Or in other words, the number of variables on the left-hand side and the number of elements in the tuple should be equal. Let us look at a few examples of packing and unpacking.

tuple assignment

Tuple Packing (Creating Tuples)

We can create a tuple in various ways by using different types of elements. Since a tuple can contain all elements of the same data type as well as of mixed data types as well. Therefore, we have multiple ways of creating tuples. Let us look at few examples of creating tuples in python which we consider as packing.

Example 1: Tuple with integers as elements

Example 2: Tuple with mixed data type

Example 3: Tuple with a tuple as an element

Example 4: Tuple with a list as an element

If there is only a single element in a tuple we should end it with a comma. Since writing, just the element inside the parenthesis will be considered as an integer.

For example,

Correct way of defining a tuple with single element is as follows:

Moreover, if you write any sequence separated by commas, python considers it as a tuple.

Browse more Topics Under Tuples and its Functions

  • Immutable Tuples
  • Creating Tuples
  • Initialising and Accessing Elements in a Tuple
  • Tuple Slicing
  • Tuple Indexing
  • Tuple Functions

Tuple Assignment (Unpacking)

Unpacking or tuple assignment is the process that assigns the values on the right-hand side to the left-hand side variables. In unpacking, we basically extract the values of the tuple into a single variable.

Frequently Asked Questions (FAQs)

Q1. State true or false:

Inserting elements in a tuple is unpacking.

Q2. What is the other name for tuple assignment?

A2. Unpacking

Q3. In unpacking what is the important condition?

A3. The number of variables on the left-hand side and the number of elements in the tuple should be equal.

Q4. Which error displays when the above condition fails?

A4. ValueError: not enough values to unpack

Customize your course in 30 seconds

Which class are you in.

tutor

  • Initialising and Accessing Elements in Tuple

Leave a Reply Cancel reply

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

Download the App

Google Play

  • Python »
  • 3.14.0a0 Documentation »
  • The Python Tutorial »
  • 4. More Control Flow Tools
  • Theme Auto Light Dark |

4. More Control Flow Tools ¶

As well as the while statement just introduced, Python uses a few more that we will encounter in this chapter.

4.1. if Statements ¶

Perhaps the most well-known statement type is the if statement. For example:

There can be zero or more elif parts, and the else part is optional. The keyword ‘ elif ’ is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif … elif … sequence is a substitute for the switch or case statements found in other languages.

If you’re comparing the same value to several constants, or checking for specific types or attributes, you may also find the match statement useful. For more details see match Statements .

4.2. for Statements ¶

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):

Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection:

4.3. The range() Function ¶

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions:

The given end point is never part of the generated sequence; range(10) generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’):

To iterate over the indices of a sequence, you can combine range() and len() as follows:

In most such cases, however, it is convenient to use the enumerate() function, see Looping Techniques .

A strange thing happens if you just print a range:

In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.

We say such an object is iterable , that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such a construct, while an example of a function that takes an iterable is sum() :

Later we will see more functions that return iterables and take iterables as arguments. In chapter Data Structures , we will discuss in more detail about list() .

4.4. break and continue Statements, and else Clauses on Loops ¶

The break statement breaks out of the innermost enclosing for or while loop.

A for or while loop can include an else clause.

In a for loop, the else clause is executed after the loop reaches its final iteration.

In a while loop, it’s executed after the loop’s condition becomes false.

In either kind of loop, the else clause is not executed if the loop was terminated by a break .

This is exemplified in the following for loop, which searches for prime numbers:

(Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if statement.)

When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions .

The continue statement, also borrowed from C, continues with the next iteration of the loop:

4.5. pass Statements ¶

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:

This is commonly used for creating minimal classes:

Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:

4.6. match Statements ¶

A match statement takes an expression and compares its value to successive patterns given as one or more case blocks. This is superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but it’s more similar to pattern matching in languages like Rust or Haskell. Only the first pattern that matches gets executed and it can also extract components (sequence elements or object attributes) from the value into variables.

The simplest form compares a subject value against one or more literals:

Note the last block: the “variable name” _ acts as a wildcard and never fails to match. If no case matches, none of the branches is executed.

You can combine several literals in a single pattern using | (“or”):

Patterns can look like unpacking assignments, and can be used to bind variables:

Study that one carefully! The first pattern has two literals, and can be thought of as an extension of the literal pattern shown above. But the next two patterns combine a literal and a variable, and the variable binds a value from the subject ( point ). The fourth pattern captures two values, which makes it conceptually similar to the unpacking assignment (x, y) = point .

If you are using classes to structure your data you can use the class name followed by an argument list resembling a constructor, but with the ability to capture attributes into variables:

You can use positional parameters with some builtin classes that provide an ordering for their attributes (e.g. dataclasses). You can also define a specific position for attributes in patterns by setting the __match_args__ special attribute in your classes. If it’s set to (“x”, “y”), the following patterns are all equivalent (and all bind the y attribute to the var variable):

A recommended way to read patterns is to look at them as an extended form of what you would put on the left of an assignment, to understand which variables would be set to what. Only the standalone names (like var above) are assigned to by a match statement. Dotted names (like foo.bar ), attribute names (the x= and y= above) or class names (recognized by the “(…)” next to them like Point above) are never assigned to.

Patterns can be arbitrarily nested. For example, if we have a short list of Points, with __match_args__ added, we could match it like this:

We can add an if clause to a pattern, known as a “guard”. If the guard is false, match goes on to try the next case block. Note that value capture happens before the guard is evaluated:

Several other key features of this statement:

Like unpacking assignments, tuple and list patterns have exactly the same meaning and actually match arbitrary sequences. An important exception is that they don’t match iterators or strings.

Sequence patterns support extended unpacking: [x, y, *rest] and (x, y, *rest) work similar to unpacking assignments. The name after * may also be _ , so (x, y, *_) matches a sequence of at least two items without binding the remaining items.

Mapping patterns: {"bandwidth": b, "latency": l} captures the "bandwidth" and "latency" values from a dictionary. Unlike sequence patterns, extra keys are ignored. An unpacking like **rest is also supported. (But **_ would be redundant, so it is not allowed.)

Subpatterns may be captured using the as keyword:

will capture the second element of the input as p2 (as long as the input is a sequence of two points)

Most literals are compared by equality, however the singletons True , False and None are compared by identity.

Patterns may use named constants. These must be dotted names to prevent them from being interpreted as capture variable:

For a more detailed explanation and additional examples, you can look into PEP 636 which is written in a tutorial format.

4.7. Defining Functions ¶

We can create a function that writes the Fibonacci series to an arbitrary boundary:

The keyword def introduces a function definition . It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented.

The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring . (More about docstrings can be found in the section Documentation Strings .) There are tools which use docstrings to automatically produce online or printed documentation, or to let the user interactively browse through code; it’s good practice to include docstrings in code that you write, so make a habit of it.

The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables and variables of enclosing functions cannot be directly assigned a value within a function (unless, for global variables, named in a global statement, or, for variables of enclosing functions, named in a nonlocal statement), although they may be referenced.

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference , not the value of the object). [ 1 ] When a function calls another function, or calls itself recursively, a new local symbol table is created for that call.

A function definition associates the function name with the function object in the current symbol table. The interpreter recognizes the object pointed to by that name as a user-defined function. Other names can also point to that same function object and can also be used to access the function:

Coming from other languages, you might object that fib is not a function but a procedure since it doesn’t return a value. In fact, even functions without a return statement do return a value, albeit a rather boring one. This value is called None (it’s a built-in name). Writing the value None is normally suppressed by the interpreter if it would be the only value written. You can see it if you really want to using print() :

It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it:

This example, as usual, demonstrates some new Python features:

The return statement returns with a value from a function. return without an expression argument returns None . Falling off the end of a function also returns None .

The statement result.append(a) calls a method of the list object result . A method is a function that ‘belongs’ to an object and is named obj.methodname , where obj is some object (this may be an expression), and methodname is the name of a method that is defined by the object’s type. Different types define different methods. Methods of different types may have the same name without causing ambiguity. (It is possible to define your own object types and methods, using classes , see Classes ) The method append() shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is equivalent to result = result + [a] , but more efficient.

4.8. More on Defining Functions ¶

It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined.

4.8.1. Default Argument Values ¶

The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:

This function can be called in several ways:

giving only the mandatory argument: ask_ok('Do you really want to quit?')

giving one of the optional arguments: ask_ok('OK to overwrite the file?', 2)

or even giving all arguments: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

This example also introduces the in keyword. This tests whether or not a sequence contains a certain value.

The default values are evaluated at the point of function definition in the defining scope, so that

will print 5 .

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

This will print

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

4.8.2. Keyword Arguments ¶

Functions can also be called using keyword arguments of the form kwarg=value . For instance, the following function:

accepts one required argument ( voltage ) and three optional arguments ( state , action , and type ). This function can be called in any of the following ways:

but all the following calls would be invalid:

In a function call, keyword arguments must follow positional arguments. All the keyword arguments passed must match one of the arguments accepted by the function (e.g. actor is not a valid argument for the parrot function), and their order is not important. This also includes non-optional arguments (e.g. parrot(voltage=1000) is valid too). No argument may receive a value more than once. Here’s an example that fails due to this restriction:

When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types — dict ) containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form *name (described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. ( *name must occur before **name .) For example, if we define a function like this:

It could be called like this:

and of course it would print:

Note that the order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call.

4.8.3. Special parameters ¶

By default, arguments may be passed to a Python function either by position or explicitly by keyword. For readability and performance, it makes sense to restrict the way arguments can be passed so that a developer need only look at the function definition to determine if items are passed by position, by position or keyword, or by keyword.

A function definition may look like:

where / and * are optional. If used, these symbols indicate the kind of parameter by how the arguments may be passed to the function: positional-only, positional-or-keyword, and keyword-only. Keyword parameters are also referred to as named parameters.

4.8.3.1. Positional-or-Keyword Arguments ¶

If / and * are not present in the function definition, arguments may be passed to a function by position or by keyword.

4.8.3.2. Positional-Only Parameters ¶

Looking at this in a bit more detail, it is possible to mark certain parameters as positional-only . If positional-only , the parameters’ order matters, and the parameters cannot be passed by keyword. Positional-only parameters are placed before a / (forward-slash). The / is used to logically separate the positional-only parameters from the rest of the parameters. If there is no / in the function definition, there are no positional-only parameters.

Parameters following the / may be positional-or-keyword or keyword-only .

4.8.3.3. Keyword-Only Arguments ¶

To mark parameters as keyword-only , indicating the parameters must be passed by keyword argument, place an * in the arguments list just before the first keyword-only parameter.

4.8.3.4. Function Examples ¶

Consider the following example function definitions paying close attention to the markers / and * :

The first function definition, standard_arg , the most familiar form, places no restrictions on the calling convention and arguments may be passed by position or keyword:

The second function pos_only_arg is restricted to only use positional parameters as there is a / in the function definition:

The third function kwd_only_args only allows keyword arguments as indicated by a * in the function definition:

And the last uses all three calling conventions in the same function definition:

Finally, consider this function definition which has a potential collision between the positional argument name and **kwds which has name as a key:

There is no possible call that will make it return True as the keyword 'name' will always bind to the first parameter. For example:

But using / (positional only arguments), it is possible since it allows name as a positional argument and 'name' as a key in the keyword arguments:

In other words, the names of positional-only parameters can be used in **kwds without ambiguity.

4.8.3.5. Recap ¶

The use case will determine which parameters to use in the function definition:

As guidance:

Use positional-only if you want the name of the parameters to not be available to the user. This is useful when parameter names have no real meaning, if you want to enforce the order of the arguments when the function is called or if you need to take some positional parameters and arbitrary keywords.

Use keyword-only when names have meaning and the function definition is more understandable by being explicit with names or you want to prevent users relying on the position of the argument being passed.

For an API, use positional-only to prevent breaking API changes if the parameter’s name is modified in the future.

4.8.4. Arbitrary Argument Lists ¶

Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences ). Before the variable number of arguments, zero or more normal arguments may occur.

Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the *args parameter are ‘keyword-only’ arguments, meaning that they can only be used as keywords rather than positional arguments.

4.8.5. Unpacking Argument Lists ¶

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the * -operator to unpack the arguments out of a list or tuple:

In the same fashion, dictionaries can deliver keyword arguments with the ** -operator:

4.8.6. Lambda Expressions ¶

Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments: lambda a, b: a+b . Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:

The above example uses a lambda expression to return a function. Another use is to pass a small function as an argument:

4.8.7. Documentation Strings ¶

Here are some conventions about the content and formatting of documentation strings.

The first line should always be a short, concise summary of the object’s purpose. For brevity, it should not explicitly state the object’s name or type, since these are available by other means (except if the name happens to be a verb describing a function’s operation). This line should begin with a capital letter and end with a period.

If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description. The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc.

The Python parser does not strip indentation from multi-line string literals in Python, so tools that process documentation have to strip indentation if desired. This is done using the following convention. The first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string. (We can’t use the first line since it is generally adjacent to the string’s opening quotes so its indentation is not apparent in the string literal.) Whitespace “equivalent” to this indentation is then stripped from the start of all lines of the string. Lines that are indented less should not occur, but if they occur all their leading whitespace should be stripped. Equivalence of whitespace should be tested after expansion of tabs (to 8 spaces, normally).

Here is an example of a multi-line docstring:

4.8.8. Function Annotations ¶

Function annotations are completely optional metadata information about the types used by user-defined functions (see PEP 3107 and PEP 484 for more information).

Annotations are stored in the __annotations__ attribute of the function as a dictionary and have no effect on any other part of the function. Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation. Return annotations are defined by a literal -> , followed by an expression, between the parameter list and the colon denoting the end of the def statement. The following example has a required argument, an optional argument, and the return value annotated:

4.9. Intermezzo: Coding Style ¶

Now that you are about to write longer, more complex pieces of Python, it is a good time to talk about coding style . Most languages can be written (or more concise, formatted ) in different styles; some are more readable than others. Making it easy for others to read your code is always a good idea, and adopting a nice coding style helps tremendously for that.

For Python, PEP 8 has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you:

Use 4-space indentation, and no tabs.

4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out.

Wrap lines so that they don’t exceed 79 characters.

This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.

Use blank lines to separate functions and classes, and larger blocks of code inside functions.

When possible, put comments on a line of their own.

Use docstrings.

Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4) .

Name your classes and functions consistently; the convention is to use UpperCamelCase for classes and lowercase_with_underscores for functions and methods. Always use self as the name for the first method argument (see A First Look at Classes for more on classes and methods).

Don’t use fancy encodings if your code is meant to be used in international environments. Python’s default, UTF-8, or even plain ASCII work best in any case.

Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code.

Table of Contents

  • 4.1. if Statements
  • 4.2. for Statements
  • 4.3. The range() Function
  • 4.4. break and continue Statements, and else Clauses on Loops
  • 4.5. pass Statements
  • 4.6. match Statements
  • 4.7. Defining Functions
  • 4.8.1. Default Argument Values
  • 4.8.2. Keyword Arguments
  • 4.8.3.1. Positional-or-Keyword Arguments
  • 4.8.3.2. Positional-Only Parameters
  • 4.8.3.3. Keyword-Only Arguments
  • 4.8.3.4. Function Examples
  • 4.8.3.5. Recap
  • 4.8.4. Arbitrary Argument Lists
  • 4.8.5. Unpacking Argument Lists
  • 4.8.6. Lambda Expressions
  • 4.8.7. Documentation Strings
  • 4.8.8. Function Annotations
  • 4.9. Intermezzo: Coding Style

Previous topic

3. An Informal Introduction to Python

5. Data Structures

  • Report a Bug
  • Show Source

Proposal: Annotate types in multiple assignment

In the latest version of Python (3.12.3), type annotation for single variable assignment is available:

However, in some scenarios like when we want to annotate the tuple of variables in return, the syntax of type annotation is invalid:

In this case, I propose two new syntaxes to support this feature:

  • Annotate directly after each variable:
  • Annotate the tuple of return:

In other programming languages, as I know, Julia and Rust support this feature in there approaches:

I’m pretty sure this has already been suggested. Did you go through the mailing list and searched for topics here? Without doing that, there’s nothing to discuss here. (Besides linking to them).

Secondly, try to not edit posts, but post a followup. Some people read these topics in mailing list mode and don’t see your edits.

  • https://mail.python.org
  • https://mail.python.org/archives

:slight_smile:

For reference, PEP 526 has a note about this in the “Rejected/Postponed Proposals” section:

Allow type annotations for tuple unpacking: This causes ambiguity: it’s not clear what this statement means: x, y: T Are x and y both of type T , or do we expect T to be a tuple type of two items that are distributed over x and y , or perhaps x has type Any and y has type T ? (The latter is what this would mean if this occurred in a function signature.) Rather than leave the (human) reader guessing, we forbid this, at least for now.

Personally I think the meaning of this is rather clear, especially when combined with an assignment, and I would like to see this.

Thank you for your valuable response, both regarding the discussion convention for Python development and the history of this feature.

I have found a related topic here: https://mail.python.org/archives/list/[email protected]/thread/5NZNHBDWK6EP67HSK4VNDTZNIVUOXMRS/

Here’s the part I find unconvincing:

Under what circumstances will fun() be hard to annotate, but a, b will be easy?

It’s better to annotate function arguments and return values, not variables. The preferred scenario is that fun() has a well-defined return type, and the type of a, b can be inferred (there is no reason to annotate it). This idea is presupposing there are cases where that’s difficult, but I’d like to see some examples where that applies.

Does this not work?

You don’t need from __future__ as of… 3.9, I think?

:confused:

3.10 if you want A | B too: PEP 604 , although I’m not sure which version the OP is using and 3.9 hasn’t reached end of life yet.

We can’t always infer it, so annotating a variable is sometimes necessary or useful. But if the function’s return type is annotated then a, b = fun() allows type-checkers to infer the types of a and b . This stuff isn’t built in to Python and is evolving as typing changes, so what was inferred in the past might be better in the future.

So my question above was: are there any scenarios where annotating the function is difficult, but annotating the results would be easy? That seems like the motivating use case.

Would it be a solution to put it on the line above? And not allow assigning on the same line? Then it better mirrors function definitions.

It’s a long thread, so it might have been suggested already.

Actually, in cases where the called function differs from the user-defined function, we should declare the types when assignment unpacking.

Here is a simplified MWE:

NOTE: In PyTorch, the __call__ function is internally wrapped from forward .

Can’t you write this? That’s shorter than writing the type annotations.

This is the kind of example I was asking for, thanks. Is the problem that typing tools don’t trace the return type through the call because the wrapping isn’t in python?

I still suggest to read the thread you linked, like I’m doing right now.

The __call__ function is not the same as forward . There might be many other preprocessing and postprocessing steps involved inside it.

Yeah, quite a bit of pre-processing in fact… unless you don’t have hooks by the looks of it:

Related Topics

Home Posts Topics Members FAQ

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use .

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.

IMAGES

  1. Tuple Unpacking in Python

    python unpack tuple assignment

  2. Unpacking a Tuple in Python

    python unpack tuple assignment

  3. Python: Unpack a tuple in several variables

    python unpack tuple assignment

  4. How to Unpack a tuple in several variables in Python

    python unpack tuple assignment

  5. Python Program to Unpack Tuple Items

    python unpack tuple assignment

  6. The Ultimate Guide to Python Tuples

    python unpack tuple assignment

VIDEO

  1. 35b. Python || Tuple || Unpack Items || Part 2

  2. Topic 32 Unpacking a Tuple

  3. python unpack collection #python #unpacking #collection #pythonprogramming #trending #feed

  4. MODULE-9 PYTHON TUPLE

  5. Write a python program to unpack a tuple in several variables

  6. 2.6 Tuple Assignment in Tamil

COMMENTS

  1. Python

    Python - Unpack Tuples Previous Next Unpacking a Tuple. When we create a tuple, we normally assign values to it. This is called "packing" a tuple: Example. Packing a tuple: fruits = ("apple", "banana", "cherry")

  2. Unpacking a Tuple in Python

    Python Tuples are very similar to lists except to some situations. Python tuples are immutable means that they can not be modified in whole program. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called ...

  3. Unpacking in Python: Beyond Parallel Assignment

    Packing and Unpacking in Python. Python allows a tuple (or list) of variables to appear on the left side of an assignment operation. Each variable in the tuple can receive one value (or more, if we use the * operator) from an iterable on the right side of the assignment. For historical reasons, Python developers used to call this tuple unpacking.

  4. Tuple Assignment, Packing, and Unpacking

    00:00 In this video, I'm going to show you tuple assignment through packing and unpacking. A literal tuple containing several items can be assigned to a single object, such as the example object here, t. 00:16 Assigning that packed object to a new tuple, unpacks the individual items into the objects in that new tuple. When unpacking, the number of variables on the left have to match the ...

  5. Python Unpacking Tuples By Examples

    Python uses the commas (,) to define a tuple, not parentheses. Unpacking tuples means assigning individual elements of a tuple to multiple variables. Use the * operator to assign remaining elements of an unpacking assignment into a list and assign it to a variable.

  6. Unpack a tuple and list in Python

    In Python, you can assign elements of a tuple or list to multiple variables. It is called sequence unpacking. 5. Data Structures - Tuples and Sequences — Python 3.11.3 documentation Basics of unpacki ...

  7. Tuple unpacking in Python

    This is called tuple unpacking . We've taken a three-item tuple and unpacked that tuple it into three variables ( x, y, and z ): >>> print(x, y, z) 2 1 3. You can think of creating a tuple as packing values together and unpacking a tuple as undoing that work. We're unpacking each of the values in our tuple above into separate variable names.

  8. Tuple Unpacking in Python

    What is Unpacking in Python? In Python, the unpacking operation is used to assign elements of a collection object like a list, tuple, dictionary, etc directly to different variables. We use the Python unpacking operator and parallel assignment to unpack collection objects. Let us discuss both ways for tuple unpacking in Python.

  9. Packing and Unpacking in Python

    In Python, unpacking is the process of extracting values from a sequence and assigning them to multiple variables. We achieve unpacking with the assignment operator on the left side and an iterable object on the left side. For example, we can unpack with a tuple like so: 1. 2. 3. myTuple = ( 1, 2, 3) a, b, c = myTuple.

  10. Tuple Unpacking

    Tuple unpacking (aka "multiple assignment" or "iterable unpacking") is often underutilized by new Python programmers. It's tempting to reach for indexes when working with tuples, lists, and other sequences. But if we know the size/shape of the tuple (or other sequence) we're working with, we can unpack it using. Tuple unpacking screencasts/articles

  11. 13.3. Tuple Assignment with Unpacking

    13.3. Tuple Assignment with Unpacking ¶. Python has a very powerful tuple assignment feature that allows a tuple of variable names on the left of an assignment statement to be assigned values from a tuple on the right of the assignment. Another way to think of this is that the tuple of values is unpacked into the variable names.

  12. Lists and Tuples in Python

    Python Tuples. Python provides another type that is an ordered collection of objects, called a tuple. ... Tuple Assignment, Packing, and Unpacking. As you have already seen above, a literal tuple containing several items can be assigned to a single object: Python >>> t = ('foo', 'bar', 'baz', 'qux')

  13. Unpack Tuples

    Unpack Tuples. 00:00 In this lesson, you'll learn about unpacking tuples. Unpacking is an interesting concept in Python that allows you to do some fun things. Let's backtrack a tiny bit and go back to how you can create a tuple literal, and you can do it by listing values separated by commas. 00:15 And generally, you would do this with ...

  14. Python TUPLE

    Python has tuple assignment feature which enables you to assign more than one variable at a time. Packing and Unpacking of Tuples; In packing, we place value into a new tuple while in unpacking we extract those values back into variables. A comparison operator in Python can work with tuples. Using tuples as keys in dictionaries

  15. Multiple assignment and tuple unpacking improve Python code readability

    Python's multiple assignment looks like this: >>> x, y = 10, 20. Here we're setting x to 10 and y to 20. What's happening at a lower level is that we're creating a tuple of 10, 20 and then looping over that tuple and taking each of the two items we get from looping and assigning them to x and y in order.

  16. python

    Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here: t = (2010, 10, 2, 11, 4, 0, 2, 41, 0) dt = datetime.datetime(*t[0:7]) This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial ...

  17. Python Tuple Unpacking: 2 Quick Methods for Unpacking Tuples

    This Article is going to clarify different ways to unpack a Tuple, following certain examples on our code snippet. Let's get into it without wasting time. Before getting started, First of all, Let's understand what a Tuple is in python. A tuple is one of the four popular in-built collections in Python among List, Set, and Dictionary.

  18. Tuple Assignment: Introduction, Tuple Packing and Examples

    Besides tuple assignment is a special feature in python. We also call this feature unpacking of tuple. The process of assigning values to a tuple is known as packing. While on the other hand, the unpacking or tuple assignment is the process that assigns the values on the right-hand side to the left-hand side variables.

  19. 4. More Control Flow Tools

    Study that one carefully! The first pattern has two literals, and can be thought of as an extension of the literal pattern shown above. But the next two patterns combine a literal and a variable, and the variable binds a value from the subject (point).The fourth pattern captures two values, which makes it conceptually similar to the unpacking assignment (x, y) = point.

  20. Ignore part of a python tuple

    This only works with one single-asterisk item in the unpack list (which receives every element not explicitly accounted for, one by one). This is because if there were more than one, there would be no way to know how many of the source elements should go into each; in the face of ambiguity, Python refuses the temptation to guess. -

  21. Proposal: Annotate types in multiple assignment

    In the latest version of Python (3.12.3), type annotation for single variable assignment is available: a: int = 1 However, in some scenarios like when we want to annotate the tuple of variables in return, the syntax of type annotation is invalid: from typing import Any def fun() -> Any: # when hard to annotate the strict type return 1, True a: int, b: bool = fun() # INVALID In this case, I ...

  22. unpacking with default values

    Do you know the "protocol" used by python while unpacking? Is it a direct assingnment? Or iterating? In CPython, at least, both, just as with normal unpack and multiple assignment. The iterable is unpacked into pieces by iterating (with knowledge of the number of targets and which is the catchall). The targets are then directly bound.

  23. Multiple Unpacking Assignment in Python when you don't know the

    Indeed, I would prefer a pure Python solution.) For the piece of code I'm looking at now, I see two complications on that straightforward scenario: I usually won't know the shape of M; and. I want to unpack a certain number of items (definitely less than all items), and I want to put the remainder into a single container

  24. 12 Essential Tuple Functions in Python to Transform Your AI Projects

    Unpack the elements of a tuple into variables, a streamlined approach to assigning model parameters. lr, epochs, batch_size = model_parameters 12. Iterating Over a Tuple ... Tuples in Python offer a robust and reliable way to manage data in AI projects, thanks to their immutability and efficiency. By applying these 12 tuple functions and ...

  25. python

    13. In my case i use the typing.cast function to type hint an unpack operation. t: tuple[int, int] = (1, 2) a, b = t. # type hint of a -> Literal[1] # type hint of b -> Literal[2] By using the cast(new_type, old_type) you can cast those ugly literals into integers. from typing import cast.