• How to Think Like a Computer Scientist: Learning with Python 3 »

9. Tuples ¶

9.1. tuples are used for grouping data ¶.

We saw earlier that we could group together pairs of values by surrounding with parentheses. Recall this example:

>>> year_born = ( "Paris Hilton" , 1981 )

This is an example of a data structure — a mechanism for grouping and organizing data to make it easier to use.

The pair is an example of a tuple . Generalizing this, a tuple can be used to group any number of items into a single compound value. Syntactically, a tuple is a comma-separated sequence of values. Although it is not necessary, it is conventional to enclose tuples in parentheses:

>>> julia = ( "Julia" , "Roberts" , 1967 , "Duplicity" , 2009 , "Actress" , "Atlanta, Georgia" )

Tuples are useful for representing what other languages often call records — some related information that belongs together, like your student record. There is no description of what each of these fields means, but we can guess. A tuple lets us “chunk” together related information and use it as a single thing.

Tuples support the same sequence operations as strings. The index operator selects an element from a tuple.

>>> julia [ 2 ] 1967

But if we try to use item assignment to modify one of the elements of the tuple, we get an error:

>>> julia [ 0 ] = "X" TypeError: 'tuple' object does not support item assignment

So like strings, tuples are immutable. Once Python has created a tuple in memory, it cannot be changed.

Of course, even if we can’t modify the elements of a tuple, we can always make the julia variable reference a new tuple holding different information. To construct the new tuple, it is convenient that we can slice parts of the old tuple and join up the bits to make the new tuple. So if julia has a new recent film, we could change her variable to reference a new tuple that used some information from the old one:

>>> julia = julia [: 3 ] + ( "Eat Pray Love" , 2010 ) + julia [ 5 :] >>> julia ("Julia", "Roberts", 1967, "Eat Pray Love", 2010, "Actress", "Atlanta, Georgia")

To create a tuple with a single element (but you’re probably not likely to do that too often), we have to include the final comma, because without the final comma, Python treats the (5) below as an integer in parentheses:

>>> tup = ( 5 ,) >>> type ( tup ) <class 'tuple'> >>> x = ( 5 ) >>> type ( x ) <class 'int'>

9.2. Tuple assignment ¶

Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an assignment to be assigned values from a tuple on the right of the assignment. (We already saw this used for pairs, but it generalizes.)

( name , surname , b_year , movie , m_year , profession , b_place ) = julia

This does the equivalent of seven assignment statements, all on one easy line. One requirement is that the number of variables on the left must match the number of elements in the tuple.

One way to think of tuple assignment is as tuple packing/unpacking.

In tuple packing, the values on the left are ‘packed’ together in a tuple:

>>> b = ( "Bob" , 19 , "CS" ) # tuple packing

In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the variables/names on the right:

>>> b = ( "Bob" , 19 , "CS" ) >>> ( name , age , studies ) = b # tuple unpacking >>> name 'Bob' >>> age 19 >>> studies 'CS'

Once in a while, it is useful to swap the values of two variables. With conventional assignment statements, we have to use a temporary variable. For example, to swap a and b :

1 2 3 temp = a a = b b = temp

Tuple assignment solves this problem neatly:

1 ( a , b ) = ( b , a )

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.

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

>>> ( a , b , c , d ) = ( 1 , 2 , 3 ) ValueError: need more than 3 values to unpack

9.3. Tuples as return values ¶

Functions can always only return a single value, but by making that value a tuple, we can effectively group together as many values as we like, and return them together. This is very useful — we often want to know some batsman’s highest and lowest score, or we want to find the mean and the standard deviation, or we want to know the year, the month, and the day, or if we’re doing some some ecological modelling we may want to know the number of rabbits and the number of wolves on an island at a given time.

For example, we could write a function that returns both the area and the circumference of a circle of radius r:

1 2 3 4 5 def f ( r ): """ Return (circumference, area) of a circle of radius r """ c = 2 * math . pi * r a = math . pi * r * r return ( c , a )

9.4. Composability of Data Structures ¶

We saw in an earlier chapter that we could make a list of pairs, and we had an example where one of the items in the tuple was itself a list:

students = [ ( "John" , [ "CompSci" , "Physics" ]), ( "Vusi" , [ "Maths" , "CompSci" , "Stats" ]), ( "Jess" , [ "CompSci" , "Accounting" , "Economics" , "Management" ]), ( "Sarah" , [ "InfSys" , "Accounting" , "Economics" , "CommLaw" ]), ( "Zuki" , [ "Sociology" , "Economics" , "Law" , "Stats" , "Music" ])]

Tuples items can themselves be other tuples. For example, we could improve the information about our movie stars to hold the full date of birth rather than just the year, and we could have a list of some of her movies and dates that they were made, and so on:

julia_more_info = ( ( "Julia" , "Roberts" ), ( 8 , "October" , 1967 ), "Actress" , ( "Atlanta" , "Georgia" ), [ ( "Duplicity" , 2009 ), ( "Notting Hill" , 1999 ), ( "Pretty Woman" , 1990 ), ( "Erin Brockovich" , 2000 ), ( "Eat Pray Love" , 2010 ), ( "Mona Lisa Smile" , 2003 ), ( "Oceans Twelve" , 2004 ) ])

Notice in this case that the tuple has just five elements — but each of those in turn can be another tuple, a list, a string, or any other kind of Python value. This property is known as being heterogeneous , meaning that it can be composed of elements of different types.

9.5. Glossary ¶

9.6. exercises ¶.

  • We’ve said nothing in this chapter about whether you can pass tuples as arguments to a function. Construct a small Python example to test whether this is possible, and write up your findings.
  • Is a pair a generalization of a tuple, or is a tuple a generalization of a pair?
  • Is a pair a kind of tuple, or is a tuple a kind of pair?

Guide to Tuples in Python

python tuple variable assignment

  • Introduction

As a Python programmer, you might already be familiar with lists, dictionaries, and sets - but don't overlook tuples! They are often overshadowed by more popular data types, but tuples can be incredibly useful in many situations.

In this guide, we'll take a deep dive into Python tuples and explore everything you need to know to use tuples in Python. We'll cover the basics of creating and accessing tuples, as well as more advanced topics like tuple operations, methods, and unpacking.
  • How to Create Tuples in Python

In Python, tuples can be created in several different ways. The simplest one is by enclosing a comma-separated sequence of values inside of parentheses:

Alternatively, you can create a tuple using the built-in tuple() function, which takes an iterable as an argument and returns a tuple:

This method is a bit more explicit and might be easier to read for Python novices.

You can also create an empty tuple by simply using the parentheses:

It's worth noting that even a tuple with a single element must include a trailing comma :

Note: Without the trailing comma, Python will interpret the parentheses as simply grouping the expression, rather than creating a tuple.

With the basics out of the way, we can take a look at how to access elements within a tuple.

  • How to Access Tuple Elements in Python

Once you have created a tuple in Python, you can access its elements using indexing, slicing, or looping . Let's take a closer look at each of these methods.

You can access a specific element of a tuple using its index. In Python, indexing starts at 0 , so the first element of a tuple has an index of 0 , the second element has an index of 1 , and so on:

If you try to access an element that is outside the bounds of the tuple, you'll get an IndexError :

Another interesting way you can access an element from the tuple is by using negative indices . That way, you are effectively indexing a tuple in reversed order, from the last element to the first:

Note: Negative indexing starts with -1 . The last element is accessed by the -1 index, the second-to-last by the -2 , and so on.

You can also access a range of elements within a tuple using slicing. Slicing works by specifying a start index and an end index, separated by a colon. The resulting slice includes all elements from the start index up to (but not including) the end index:

You can also use negative indices to slice from the end of the tuple:

Advice: If you want to learn more about slicing in Python, you should definitely take a look at our article "Python: Slice Notation on List" .

  • Looping Through Tuples

Finally, you can simply loop through all the elements of a tuple using a for loop:

This will give us:

In the next section, we'll explore the immutability of tuples and how to work around it.

  • Can I Modify Tuples in Python?

One of the defining characteristics of tuples in Python is their immutability . Once you have created a tuple, you cannot modify its contents . This means that you cannot add, remove, or change elements within a tuple. Let's look at some examples to see this in action:

As you can see, attempting to modify a tuple raises appropriate errors - TypeError or AttributeError . So what can you do if you need to change the contents of a tuple?

Note: It's important to note that all of the methods demonstrated below are simply workarounds. There is no direct way to modify a tuple in Python, and the methods discussed here effectively create new objects that simulate the modification of tuples.

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!

One approach is to convert the tuple to a mutable data type, such as a list, make the desired modifications, and then convert it back to a tuple:

This approach allows you to make modifications to the contents of the tuple, but it comes with a trade-off - the conversion between the tuple and list can be expensive in terms of time and memory. So use this technique sparingly, and only when absolutely necessary.

Another approach is to use tuple concatenation to create a new tuple that includes the desired modifications:

In this example, we used tuple concatenation to create a new tuple that includes the modified element (4,) followed by the remaining elements of the original tuple. This approach is less efficient than modifying a list, but it can be useful when you only need to make a small number of modifications.

Remember, tuples are immutable, and examples shown in this section are just (very inefficient) workarounds, so always be careful when modifying tuples. More specifically, if you find yourself in need of changing a tuple in Python, you probably shouldn't be using a tuple in the first place.
  • What Operations Can I Use on Tuples in Python?

Even though tuples are immutable, there are still a number of operations that you can perform on them. Here are some of the most commonly used tuple operations in Python:

  • Tuple Concatenation

You can concatenate two or more tuples using the + operator. The result is a new tuple that contains all of the elements from the original tuples:

  • Tuple Repetition

You can repeat a tuple a certain number of times using the * operator. The result is a new tuple that contains the original tuple repeated the specified number of times:

  • Tuple Membership

You can check if an element is present in a tuple using the in operator. The result is a Boolean value ( True or False ) indicating whether or not the element is in the tuple:

  • Tuple Comparison

You can compare two tuples using the standard comparison operators ( < , <= , > , >= , == , and != ). The comparison is performed element-wise, and the result is a Boolean value indicating whether or not the comparison is true:

  • Tuple Unpacking

You can unpack a tuple into multiple variables using the assignment operator ( = ). The number of variables must match the number of elements in the tuple, otherwise a ValueError will be raised. Here's an example:

  • Tuple Methods

In addition to the basic operations that you can perform on tuples, there are also several built-in methods that are available for working with tuples in Python. In this section, we'll take a look at some of the most commonly used tuple methods.

The count() method returns the number of times a specified element appears in a tuple:

The index() method returns the index of the first occurrence of a specified element in a tuple. If the element is not found, a ValueError is raised:

The len() function returns the number of elements in a tuple:

The sorted() function returns a new sorted list containing all elements from the tuple:

Note: The sorted() function returns a list, which is then converted back to a tuple using the tuple() constructor.

  • min() and max()

The min() and max() functions return the smallest and largest elements in a tuple, respectively:

These are just a few examples of the methods that are available for working with tuples in Python. By combining these methods with the various operations available for tuples, you can perform a wide variety of tasks with these versatile data types.

One of the interesting features of tuples in Python that we've discussed is that you can "unpack" them into multiple variables at once. This means that you can assign each element of a tuple to a separate variable in a single line of code. This can be a convenient way to work with tuples when you need to access individual elements or perform operations on them separately.

Let's recall the example from the previous section:

In this example, we created a tuple my_tuple with three elements. Then, we "unpack" the tuple by assigning each element to a separate variables a , b , and c in a single line of code. Finally, we verified that the tuple has been correctly unpacked.

One interesting use case of tuple unpacking is that we can use it to swap the values of two variables, without needing a temporary variable :

Here, we use tuple unpacking to swap the values of a and b . The expression a, b = b, a creates a tuple with the values of b and a , which is then unpacked into the variables a and b in a single line of code.

Another useful application of tuple unpacking is unpacking a tuple into another tuple . This can be helpful when you have a tuple with multiple elements, and you want to group some of those elements together into a separate tuple:

We have a tuple my_tuple with five elements. We use tuple unpacking to assign the first two elements to the variables a and b , and the remaining elements to the variable c using the * operator. The * operator is used to "unpack" the remaining elements of the tuple into a new tuple, which is assigned to the variable c .

This is also an interesting way to return multiple values/variables from a function, allowing the caller to then decide how the return values should be unpacked and assigned from their end.

Tuples are one of fundamental data types in Python. They allow you to store a collection of values in a single container. They're similar to lists, but with a few important differences - tuples are immutable, and they're usually used to store a fixed set of values that belong together.

In this guide, we've covered the basics of working with tuples in Python, including creating tuples, accessing their elements, modifying them, and performing operations on them. We've also explored some of the more advanced features of tuples, such as tuple unpacking.

Tuples may not be the most glamorous data type in Python, but they're certainly effective when you know how and when to use them. So the next time you're working on a Python project, remember to give tuples a try. Who knows, they may just become your new favorite data type!

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.

In this article

python tuple variable 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.

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons
  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

10.3: Tuple Assignment

  • Last updated
  • Save as PDF
  • Page ID 8646

  • Chuck Severance
  • University of Michigan

One of the unique syntactic features of the Python language is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when the left side is a sequence.

In this example we have a two-element list (which is a sequence) and assign the first and second elements of the sequence to the variables x and y in a single statement.

It is not magic, Python roughly translates the tuple assignment syntax to be the following: 2

Stylistically when we use a tuple on the left side of the assignment statement, we omit the parentheses, but the following is an equally valid syntax:

A particularly clever application of tuple assignment allows us to swap the values of two variables in a single statement:

Both sides of this statement are tuples, but the left side is a tuple of variables; the right side is a tuple of expressions. Each value on the right side is assigned to its respective variable on the left side. All the expressions on the right side are evaluated before any of the assignments.

The number of variables on the left and the number of values on the right must be the same:

More generally, the right side can be any kind of sequence (string, list, or tuple). For example, to split an email address into a user name and a domain, you could write:

The return value from split is a list with two elements; the first element is assigned to uname , the second to domain .

  • 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

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables, Constants and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers, Type Conversion and Mathematics
  • Python List

Python Tuple

  • Python Sets
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python tuple()

Python Tuple index()

Python Tuple count()

  • Python Lists Vs Tuples

Python del Statement

  • Python Dictionary items()

A tuple is a collection of data similar to a Python list . The only difference is that we cannot modify a tuple once it has been created.

  • Create a Python Tuple

We create a tuple by placing items inside parentheses () . For example,

More on Tuple Creation

We can also create a tuple using a tuple() constructor. For example,

Here are the different types of tuples we can create in Python.

Empty Tuple

Tuple of different data types

Tuple of mixed data types

Tuple Characteristics

Tuples are:

  • Ordered - They maintain the order of elements.
  • Immutable - They cannot be changed after creation.
  • Allow duplicates - They can contain duplicate values.
  • Access Tuple Items

Each item in a tuple is associated with a number, known as a index .

The index always starts from 0 , meaning the first item of a tuple is at index 0 , the second item is at index 1, and so on.

Index of Tuple Item

Access Items Using Index

We use index numbers to access tuple items. For example,

Access Tuple Items

Tuple Cannot be Modified

Python tuples are immutable (unchangeable). We cannot add, change, or delete items of a tuple.

If we try to modify a tuple, we will get an error. For example,

  • Python Tuple Length

We use the len() function to find the number of items present in a tuple. For example,

  • Iterate Through a Tuple

We use the for loop to iterate over the items of a tuple. For example,

More on Python Tuple

We use the in keyword to check if an item exists in the tuple. For example,

  • yellow is not present in colors , so, 'yellow' in colors evaluates to False
  • red is present in colors , so, 'red' in colors evaluates to True

Python Tuples are immutable - we cannot change the items of a tuple once created.

If we try to do so, we will get an error. For example,

We cannot delete individual items of a tuple. However, we can delete the tuple itself using the del statement. For example,

Here, we have deleted the animals tuple.

When we want to create a tuple with a single item, we might do the following:

But this would not create a tuple; instead, it would be considered a string .

To solve this, we need to include a trailing comma after the item. For example,

  • Python Tuple Methods

Table of Contents

  • Introduction

Video: Python Lists and Tuples

Sorry about that.

Related Tutorials

Python Library

Python Tutorial

5 Best Ways to Assign Python Tuple to Multiple Variables

💡 Problem Formulation: In Python, developers often need to assign the elements of a tuple to separate variables in a clean and readable way. This task is common when dealing with function returns or data structures that inherently group multiple items, for example, ( ('apple', 'banana', 'cherry') ). The desired output is having each fruit assigned to its own variable, like fruit1 = 'apple' , fruit2 = 'banana' , and fruit3 = 'cherry' . This article explores the best ways to accomplish this.

Method 1: Basic Tuple Unpacking

Tuple unpacking is a straightforward and pythonic way to assign elements of a tuple to multiple variables. Each variable gets the corresponding element based on its position in the tuple. This method is ideal when you know the exact length of the tuple and want to assign each element to a named variable.

Here’s an example:

The code snippet above shows how each fruit string in the fruits tuple is assigned to an individual variable. This method requires the number of variables on the left-hand side to match the number of elements in the tuple, otherwise, a ValueError will be thrown.

Method 2: Using Asterisk (*) for Excess Items

Python’s extended unpacking feature, introduced in PEP 3132, lets you handle tuples with unknown or varying lengths. By placing an asterisk (*) before a variable, you can assign a list of all excess items to that variable, which is useful when you’re only interested in the first few elements.

This code snippet assigns the first two elements of the fruits tuple to fruit1 and fruit2 , respectively, and all remaining elements to the list remaining_fruits . It’s especially convenient when the number of elements exceeds the number of variables.

Method 3: Using _ for Ignored Values

In Python, the underscore ( _ ) is commonly used as a placeholder for unwanted tuple items during unpacking. When you don’t need certain elements, this method can increase clarity by indicating that some elements are intentionally ignored.

The snippet above shows how the first name, last name, and status values are unpacked into their respective variables. The email, which is not needed, is assigned to _ , thereby ignoring it without having to allocate a named variable.

Method 4: Using the zip() Function

The zip() function can be used to unpack tuple elements when you’re dealing with multiple tuples that need to be processed in parallel. Each tuple is paired with a corresponding element from the other tuple(s), ideal for simultaneous variable assignments from multiple tuples.

The example demonstrates how zip() is used to combine items from the fruits and colors tuples, allowing unpacking to corresponding variable pairs, which could be useful in a context where the relationship between two characteristics matters.

Bonus One-Liner Method 5: Using Chain from Itertools

The itertools.chain() function is handy for flattening multiple tuples into a single iterable, which can then be unpacked to variables. This method is particularly useful when you want to combine several tuples before unpacking and when one-liners are desired for simplicity or brevity.

This code merges two tuples and then immediately unpacks them into separate variables, showcasing the utility of chain() for combining iterables in a one-liner pattern.

Summary/Discussion

  • Method 1: Basic Tuple Unpacking. Straightforward and clean. Limited to scenarios with a known number of tuple elements.
  • Method 2: Using Asterisk (*) for Excess Items. Flexible and pythonic. It handles tuples with varying lengths, but extra items are grouped into a list, potentially adding complexity if individual variables are needed.
  • Method 3: Using _ for Ignored Values. Increases readability by signaling ignored elements. However, it only makes sense when ignoring tuple elements, not when all values are needed.
  • Method 4: Using the zip() Function. Good for handling and processing multiple tuples in parallel. It can become less readable if too many tuples are processed simultaneously.
  • Bonus One-Liner Method 5: Using Chain from Itertools. Excellent for combining multiple tuples before unpacking. It adds a dependency on the itertools library.

Emily Rosemary Collins is a tech enthusiast with a strong background in computer science, always staying up-to-date with the latest trends and innovations. Apart from her love for technology, Emily enjoys exploring the great outdoors, participating in local community events, and dedicating her free time to painting and photography. Her interests and passion for personal growth make her an engaging conversationalist and a reliable source of knowledge in the ever-evolving world of technology.

Digital Design Journal

Tuple Assignment Python [With Examples]

Tuple assignment is a feature that allows you to assign multiple variables simultaneously by unpacking the values from a tuple (or other iterable) into those variables.

Tuple assignment is a concise and powerful way to assign values to multiple variables in a single line of code.

Here’s how it works:

In this example, the values from the my_tuple tuple are unpacked and assigned to the variables a , b , and c in the same order as they appear in the tuple.

Tuple assignment is not limited to tuples; it can also work with other iterable types like lists:

Tuple assignment can be used to swap the values of two variables without needing a temporary variable:

Tuple assignment is a versatile feature in Python and is often used when you want to work with multiple values at once, making your code more readable and concise.

Tuple Assignment Python Example

Here are some examples of tuple assignment in Python:

Example 1: Basic Tuple Assignment

Example 2: Multiple Variables Assigned at Once

Example 3: Swapping Values

Example 4: Unpacking a Tuple Inside a Loop

Example 5: Ignoring Unwanted Values

These examples demonstrate various uses of tuple assignment in Python, from basic variable assignment to more advanced scenarios like swapping values or ignoring unwanted elements in the tuple. Tuple assignment is a powerful tool for working with structured data in Python.

  • Python Tuple Vs List Performance
  • Subprocess Python Stdout
  • Python Subprocess Stderr
  • Python Asyncio Subprocess [Asynchronous Subprocesses]
  • Subprocess.popen And Subprocess.run
  • Python Subprocess.popen
  •  Difference Between Subprocess Popen And Call
  • 5 Tuple Methods in Python [Explained]
  • Python List to Tuple
  • Python Tuple Append
  • Python Unpack Tuple Into Arguments
  • Python Concatenate Tuples

Aniket Singh

Aniket Singh holds a B.Tech in Computer Science & Engineering from Oriental University. He is a skilled programmer with a strong coding background, having hands-on experience in developing advanced projects, particularly in Python and the Django framework. Aniket has worked on various real-world industry projects and has a solid command of Python, Django, REST API, PostgreSQL, as well as proficiency in C and C++. He is eager to collaborate with experienced professionals to further enhance his skills.

View all posts

Leave a Comment Cancel reply

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

Tuples in Python

  • Python - Create a List of Tuples
  • Create a tuple from string and list - Python
  • Access front and rear element of Python tuple
  • Python - Element Index in Range Tuples
  • Unpacking a Tuple in Python
  • Python | Unpacking nested tuples
  • Python | Slice String from Tuple ranges
  • Python - Clearing a tuple
  • Python program to remove last element from Tuple
  • Python | Removing duplicates from tuple
  • Python - AND operation between Tuples
  • Python - Sum of tuple elements
  • Python | Ways to concatenate tuples
  • Python | Repeating tuples N times
  • Python Membership and Identity Operators
  • Python | Compare tuples
  • Python | Join tuple elements in a list
  • Python - Join Tuples if similar initial element
  • Python - Create list of tuples using for loop
  • How we can iterate through list of tuples in Python
  • Python Tuple Methods
  • Python Tuple Exercise

Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable.

Creating Python Tuples

There are various ways by which you can create a tuple in Python . They are as follows:

  • Using round brackets
  • With one item
  • Tuple Constructor

Create Tuples using Round Brackets ()

To create a tuple we will use () operators.

Create a Tuple With One Item

Python 3.11 provides us with another way to create a Tuple.

Here, in the above snippet we are considering a variable called values which holds a tuple that consists of either int or str, the ‘…’ means that the tuple will hold more than one int or str.

Note: In case your generating a tuple with a single element, make sure to add a comma after the element. Let us see an example of the same.

Tuple Constructor in Python

To create a tuple with a Tuple constructor, we will pass the elements as its parameters.

What is Immutable in Tuples?

Tuples in Python are similar to Python lists but not entirely. Tuples are immutable and ordered and allow duplicate values. Some Characteristics of Tuples in Python.

  • We can find items in a tuple since finding any item does not make changes in the tuple.
  • One cannot add items to a tuple once it is created. 
  • Tuples cannot be appended or extended.
  • We cannot remove items from a tuple once it is created. 

Let us see this with an example.

Python tuples are ordered and we can access their elements using their index values. They are also immutable, i.e., we cannot add, remove and change the elements once declared in the tuple, so when we tried to add an element at index 1, it generated the error.

Accessing Values in Python Tuples

Tuples in Python provide two ways by which we can access the elements of a tuple.

  • Using a positive index
  • Using a negative index

Python Access Tuple using a Positive Index

Using square brackets we can get the values from tuples in Python.

Access Tuple using Negative Index

In the above methods, we use the positive index to access the value in Python, and here we will use the negative index within [].

Different Operations Related to Tuples

Below are the different operations related to tuples in Python:

  • Concatenation
  • Finding the length
  • Multiple Data Types with tuples
  • Conversion of lists to tuples

Tuples in a Loop

Concatenation of python tuples.

To Concatenation of Python Tuples, we will use plus operators(+).

Nesting of Python Tuples

A nested tuple in Python means a tuple inside another tuple.

Repetition Python Tuples

We can create a tuple of multiple same elements from a single element in that tuple.

Try the above without a comma and check. You will get tuple3 as a string ‘pythonpythonpython’. 

Slicing Tuples in Python

Slicing a Python tuple means dividing a tuple into small tuples using the indexing method.

In this example, we sliced the tuple from index 1 to the last element. In the second print statement, we printed the tuple using reverse indexing. And in the third print statement, we printed the elements from index 2 to 4.

Note: In Python slicing, the end index provided is not included.

Deleting a Tuple in Python

In this example, we are deleting a tuple using ‘ del’ keyword . The output will be in the form of error because after deleting the tuple, it will give a NameError.

Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple using Del keyword.

Finding the Length of a Python Tuple

To find the length of a tuple, we can use Python’s len() function and pass the tuple as the parameter.

Multiple Data Types With Tuple

Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple datatypes.

Converting a List to a Tuple

We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as its parameters.

Tuples take a single parameter which may be a list, string, set, or even a dictionary(only keys are taken as elements), and converts them to a tuple.

We can also create a tuple with a single element in it using loops .

Please Login to comment...

Similar reads.

  • python-tuple
  • School Programming

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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.

Get my tuple unpacking exercise

I won’t share you info with others (see the Python Morsels Privacy Policy for details). This form is reCAPTCHA protected (Google Privacy Policy & TOS )

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.

logo

Learning Python by doing

  • suggest edit

This notebook presents three more built-in types, tuples , sets , and relations , and then shows how these data types and previous ones work together.

Additionally, the gather and scatter operators, a useful feature for variable-length argument lists, are presented.

Tuples are Immutable #

A tuple is a sequence of values.

The values in a tuple can be of arbitrary types.

The elements of a tuple are indexed via integers, in that they resemble lists.

Tuples are immutable , whereas lists are mutable .

The following cells show a tuple with 5 elements, in the second cell parentheses are used to denote the tuple.

Do It Yourself!

Create a tuple with the name of some countries as elements.

If you want to create a tuple with just one element, then you have to add a comma as terminator

A single value between parantheses is not a tuple.

Create a tuple with your name as single element.

You can create a tuple via the built-in function tuple .

If the argument of the tuple function is a sequence (string, list, or tuple), the result is a tuple with the elements of the sequence.

Create a tuple out of the artists list.

tuple is a built-in function, so avoid using tuple as variable name.

Most list operators also work on tuples. The bracket operator indexes an element.

The slice operator allows you to select a range of elements.

Use slicing to only return the values of ‘Adele’ and ‘Bon Jovi’ from your artists tuple.

Tuples are immutable, so if you try to assign a value to a tuple element, you will get an error message.

In order to replace elements in a tuple, you have to create a new one.

So, tuples have a strong resemblance with strings .

This statement makes a new tuple and then makes t refer to it.

Add a new artists to your artists tuple.

Comparing Tuples #

The relational operators work with tuples and other sequences; Python starts by comparing the first element from each sequence.

If they are equal, it goes on to the next elements, and so on, until it finds elements that differ.

Subsequent elements are not considered (even if they are really big).

The sort() function works in the same manner.

It sorts based on the first element. If there is a tie it considers the second one, and so on.

This feature is used within the DSU pattern :

Decorate a sequence by creating a list of tuples with sort keys preceding the elements of the sequence.

Sort the list of tuples with the sort() function.

Undecorate by extracting the elements of the sequence.

In this example, we want to sort words from the longest to the shortest.

To do so, we consider our text (i.e. poem ) and we create a list of words with the split() function.

Then, we iterate over the list and we append a tuple to the length_words list.

This tuple has the length of the word as first element, and the word itself as second element. With this we decorate the original sequence of words.

Afterwards, we sort the list of tuples (i.e. length_words ).

Finally, we iterate over the list of tuples (i.e. length_words ) to undecorate te sequence, and we append each word to the new list sort_words .

Let’s consider again the poem variable. We want to sort its words based on the number of times that the letter a appears on it. Use the DSU pattern.

Tuple Assignment #

Python allows us to have a tuple on the left side of an assignment.

In this way, we can assign more than one variable at a time.

We usually omit the use of parentheses on the left side of an assignment statement.

If you want to swap the value of two variables you can use a temporary variable.

You can also use the tuple assignment .

The left side is a tuple of variables; the right side is a tuple of expressions.

Each value is assigned to its respective variable.

All the expressions on the right side are evaluated before any of the assignments.

The tuple assignment requires that both sides have the same number of elements.

More generally, the right side can be any kind of sequence (string, list or tuple).

For example, to split an email address into a user name and a domain, you could write:

The return value from split is a list with two elements; the first element is assigned to uname , the second to domain .

Assign the elements of the list artist to a tuple with three elements. Then, rearrange the tuple so we get them in the right order, i.e. The, Rolling, Stones.

Tuples as Return Values #

A function/method can return only one single value.

By means of a tuple a function can return a collection of values.

Suppose you want to divide two integers and compute the quotient and remainder.

It is inefficient to compute x / y and then x % y .

It is better to compute them both at the same time via the function divmod .

Using the tuple assignment you can obtain the results separately.

The calculation of the min and max can be captured as follows, where min and max are built-in functions for finding the smallest and largest elements of a sequence.

Create a function that takes a list of strings and returns the shortest and longest words as a tuple.

Variable-length Argument Tuples #

Functions/methods can take a variable number of arguments.

A parameter name that starts with a * gathers arguments into a tuple.

The gather argument can have any name, but often the name args is used.

The inverse of the gather is scatter , it splits the tuple in separate elements.

A number of built-in functions use variable-length argument tuples.

An exception is the sum function.

Create a function that receives a variable number of arguments and multiples all received items. Then, it returns the result.

Lists and Tuples #

zip is a built-in function that takes two or more sequences and returns a list of tuples where each tuple contains one element from each sequence.

The name of the function refers to a zipper.

The result of the zip is a zip object that knows how to iterate through the elements.

The best way is to use a for loop.

Observe the subtle difference between the code in the cell above and below, by running the cell below twice in a row.

The variable z does not contain a value representing the list of tuples, but the zip object.

A zip object is an iterator that iterates through a sequence.

There are 2 major differences:

indexing an element is not supported

the iteration cannot be repeated

If you want to use list operators and methods, you can use a zip object to make a list.

The result is a list of tuples consisting of a character and a digit.

If the lists you are zipping have not the same length, the result is a zip object with the length of the shortest list.

You can use tuple assignment in a for loop to traverse a list of tuples.

If you combine zip , a for loop and a tuple assignment, you get a useful idiom for traversing two (or more) sequences at the same time.

The function has_match() takes two sequences, t1 and t2 , and returns True if there is an index i such that t1[i] == t2[i] .

The following cell shows the code if you want the index to be returned instead of a boolean value.

Use the zip function to create a list of tuples out of nums1 and nums2 . Then, iterate over the zip object and return True if there is at least one pair where the first number is divisible by the second one, False otherwise.

If you need to traverse the elements of a sequence and their indices, you can use the built-in function enumerate .

The enumerate function has the same characteristics as the zip function.

It creates an enumerate object of which the elements can be accessed via iteration.

Each pair contains an index (starting from 0) and an element from the given sequence.

Create a function that receives a list of integers and an integer as parameters. Use the enumerate function to traverse that list and return the position of the first number that is equal to the one received as parameter. If the number is not part of the list return -1.

Dictionaries and Tuples #

Dictionaries are very handy to store values using keys.

You can transform a dictionary into a dict_items object , which is similar to the zip object and the enumerate object .

You can transform a dictionary into a dict_items object via the built-in function items .

This function returns a sequence of tuples, where each tuple is a key-value pair.

The dict_items is an iterator that iterates over the key-value pairs.

You can use a list of tuples to create a dictionary.

Combining dict with zip yields a concise way to create a dictionary.

The dictionary method update takes a list of tuples and adds them, as key-value pairs, to an existing dictionary.

It is common to use tuples as keys in dictionaries (primarily because you cannot use lists).

For example, a telephone directory might map from last-name, first-name pairs to telephone numbers.

Assuming that we have defined last , first and number , we could write the following statement.

Take the eng_sp dictionary and based on it create the sp_eng which swaps english words by spanish words. For instance, instead of having ‘hello’ : ‘hola’, the sp_eng dictionary will have ‘hola’ : ‘hello’. Use the items method to achieve this goal.

This Jupyter Notebook is based on Chapter 10 of [ Sev16 ] and on Chapters 12, 13 and 19 of [ Dow15 ] .

python tuple variable 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" >

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.

Multiple Assignment Syntax in Python

  • python-tricks

The multiple assignment syntax, often referred to as tuple unpacking or extended unpacking, is a powerful feature in Python. There are several ways to assign multiple values to variables at once.

Let's start with a first example that uses extended unpacking . This syntax is used to assign values from an iterable (in this case, a string) to multiple variables:

a : This variable will be assigned the first element of the iterable, which is 'D' in the case of the string 'Devlabs'.

*b : The asterisk (*) before b is used to collect the remaining elements of the iterable (the middle characters in the string 'Devlabs') into a list: ['e', 'v', 'l', 'a', 'b']

c : This variable will be assigned the last element of the iterable: 's'.

The multiple assignment syntax can also be used for numerous other tasks:

Swapping Values

This swaps the values of variables a and b without needing a temporary variable.

Splitting a List

first will be 1, and rest will be a list containing [2, 3, 4, 5] .

Assigning Multiple Values from a Function

This assigns the values returned by get_values() to x, y, and z.

Ignoring Values

Here, you're ignoring the first value with an underscore _ and assigning "Hello" to the important_value . In Python, the underscore is commonly used as a convention to indicate that a variable is being intentionally ignored or is a placeholder for a value that you don't intend to use.

Unpacking Nested Structures

This unpacks a nested structure (Tuple in this example) into separate variables. We can use similar syntax also for Dictionaries:

In this case, we first extract the 'person' dictionary from data, and then we use multiple assignment to further extract values from the nested dictionaries, making the code more concise.

Extended Unpacking with Slicing

first will be 1, middle will be a list containing [2, 3, 4], and last will be 5.

Split a String into a List

*split, is used for iterable unpacking. The asterisk (*) collects the remaining elements into a list variable named split . In this case, it collects all the characters from the string.

The comma , after *split is used to indicate that it's a single-element tuple assignment. It's a syntax requirement to ensure that split becomes a list containing the characters.

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

Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List , Set , and Dictionary , all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable .

Tuples are written with round brackets.

Create a Tuple:

Tuple Items

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0] , the second item has index [1] etc.

When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.

Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.

Allow Duplicates

Since tuples are indexed, they can have items with the same value:

Tuples allow duplicate values:

Advertisement

Tuple Length

To determine how many items a tuple has, use the len() function:

Print the number of items in the tuple:

Create Tuple With One Item

To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.

One item tuple, remember the comma:

Tuple Items - Data Types

Tuple items can be of any data type:

String, int and boolean data types:

A tuple can contain different data types:

A tuple with strings, integers and boolean values:

From Python's perspective, tuples are defined as objects with the data type 'tuple':

What is the data type of a tuple?

The tuple() Constructor

It is also possible to use the tuple() constructor to make a tuple.

Using the tuple() method to make a tuple:

Python Collections (Arrays)

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered** and changeable. No duplicate members.

*Set items are unchangeable, but you can remove and/or add items whenever you like.

**As of Python version 3.7, dictionaries are ordered . In Python 3.6 and earlier, dictionaries are unordered .

When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.

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 Enhancement Proposals

  • Python »
  • PEP Index »

PEP 526 – Syntax for Variable Annotations

Notice for reviewers, global and local variable annotations, class and instance variable annotations, annotating expressions, where annotations aren’t allowed, variable annotations in stub files, preferred coding style for variable annotations, changes to standard library and documentation, other uses of annotations, rejected/postponed proposals, backwards compatibility, implementation.

This PEP has been provisionally accepted by the BDFL. See the acceptance message for more color: https://mail.python.org/pipermail/python-dev/2016-September/146282.html

This PEP was drafted in a separate repo: https://github.com/phouse512/peps/tree/pep-0526 .

There was preliminary discussion on python-ideas and at https://github.com/python/typing/issues/258 .

Before you bring up an objection in a public forum please at least read the summary of rejected ideas listed at the end of this PEP.

PEP 484 introduced type hints, a.k.a. type annotations. While its main focus was function annotations, it also introduced the notion of type comments to annotate variables:

This PEP aims at adding syntax to Python for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments:

PEP 484 explicitly states that type comments are intended to help with type inference in complex cases, and this PEP does not change this intention. However, since in practice type comments have also been adopted for class variables and instance variables, this PEP also discusses the use of type annotations for those variables.

Although type comments work well enough, the fact that they’re expressed through comments has some downsides:

  • Text editors often highlight comments differently from type annotations.
  • There’s no way to annotate the type of an undefined variable; one needs to initialize it to None (e.g. a = None # type: int ).
  • Variables annotated in a conditional branch are difficult to read: if some_value : my_var = function () # type: Logger else : my_var = another_function () # Why isn't there a type here?
  • Since type comments aren’t actually part of the language, if a Python script wants to parse them, it requires a custom parser instead of just using ast .
  • Type comments are used a lot in typeshed. Migrating typeshed to use the variable annotation syntax instead of type comments would improve readability of stubs.
  • In situations where normal comments and type comments are used together, it is difficult to distinguish them: path = None # type: Optional[str] # Path to module source
  • It’s impossible to retrieve the annotations at runtime outside of attempting to find the module’s source code and parse it at runtime, which is inelegant, to say the least.

The majority of these issues can be alleviated by making the syntax a core part of the language. Moreover, having a dedicated annotation syntax for class and instance variables (in addition to method annotations) will pave the way to static duck-typing as a complement to nominal typing defined by PEP 484 .

While the proposal is accompanied by an extension of the typing.get_type_hints standard library function for runtime retrieval of annotations, variable annotations are not designed for runtime type checking. Third party packages will have to be developed to implement such functionality.

It should also be emphasized that Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention. Type annotations should not be confused with variable declarations in statically typed languages. The goal of annotation syntax is to provide an easy way to specify structured type metadata for third party tools.

This PEP does not require type checkers to change their type checking rules. It merely provides a more readable syntax to replace type comments.

Specification

Type annotation can be added to an assignment statement or to a single expression indicating the desired type of the annotation target to a third party type checker:

This syntax does not introduce any new semantics beyond PEP 484 , so that the following three statements are equivalent:

Below we specify the syntax of type annotations in different contexts and their runtime effects.

We also suggest how type checkers might interpret annotations, but compliance to these suggestions is not mandatory. (This is in line with the attitude towards compliance in PEP 484 .)

The types of locals and globals can be annotated as follows:

Being able to omit the initial value allows for easier typing of variables assigned in conditional branches:

Note that, although the syntax does allow tuple packing, it does not allow one to annotate the types of variables when tuple unpacking is used:

Omitting the initial value leaves the variable uninitialized:

However, annotating a local variable will cause the interpreter to always make it a local:

as if the code were:

Duplicate type annotations will be ignored. However, static type checkers may issue a warning for annotations of the same variable by a different type:

Type annotations can also be used to annotate class and instance variables in class bodies and methods. In particular, the value-less notation a: int allows one to annotate instance variables that should be initialized in __init__ or __new__ . The proposed syntax is as follows:

Here ClassVar is a special class defined by the typing module that indicates to the static type checker that this variable should not be set on instances.

Note that a ClassVar parameter cannot include any type variables, regardless of the level of nesting: ClassVar[T] and ClassVar[List[Set[T]]] are both invalid if T is a type variable.

This could be illustrated with a more detailed example. In this class:

stats is intended to be a class variable (keeping track of many different per-game statistics), while captain is an instance variable with a default value set in the class. This difference might not be seen by a type checker: both get initialized in the class, but captain serves only as a convenient default value for the instance variable, while stats is truly a class variable – it is intended to be shared by all instances.

Since both variables happen to be initialized at the class level, it is useful to distinguish them by marking class variables as annotated with types wrapped in ClassVar[...] . In this way a type checker may flag accidental assignments to attributes with the same name on instances.

For example, annotating the discussed class:

As a matter of convenience (and convention), instance variables can be annotated in __init__ or other methods, rather than in the class:

The target of the annotation can be any valid single assignment target, at least syntactically (it is up to the type checker what to do with this):

Note that even a parenthesized name is considered an expression, not a simple name:

It is illegal to attempt to annotate variables subject to global or nonlocal in the same function scope:

The reason is that global and nonlocal don’t own variables; therefore, the type annotations belong in the scope owning the variable.

Only single assignment targets and single right hand side values are allowed. In addition, one cannot annotate variables used in a for or with statement; they can be annotated ahead of time, in a similar manner to tuple unpacking:

As variable annotations are more readable than type comments, they are preferred in stub files for all versions of Python, including Python 2.7. Note that stub files are not executed by Python interpreters, and therefore using variable annotations will not lead to errors. Type checkers should support variable annotations in stubs for all versions of Python. For example:

Annotations for module level variables, class and instance variables, and local variables should have a single space after corresponding colon. There should be no space before the colon. If an assignment has right hand side, then the equality sign should have exactly one space on both sides. Examples:

  • Yes: code : int class Point : coords : Tuple [ int , int ] label : str = '<unknown>'
  • No: code : int # No space after colon code : int # Space before colon class Test : result : int = 0 # No spaces around equality sign
  • A new covariant type ClassVar[T_co] is added to the typing module. It accepts only a single argument that should be a valid type, and is used to annotate class variables that should not be set on class instances. This restriction is ensured by static checkers, but not at runtime. See the classvar section for examples and explanations for the usage of ClassVar , and see the rejected section for more information on the reasoning behind ClassVar .
  • Function get_type_hints in the typing module will be extended, so that one can retrieve type annotations at runtime from modules and classes as well as functions. Annotations are returned as a dictionary mapping from variable or arguments to their type hints with forward references evaluated. For classes it returns a mapping (perhaps collections.ChainMap ) constructed from annotations in method resolution order.
  • Recommended guidelines for using annotations will be added to the documentation, containing a pedagogical recapitulation of specifications described in this PEP and in PEP 484 . In addition, a helper script for translating type comments into type annotations will be published separately from the standard library.

Runtime Effects of Type Annotations

Annotating a local variable will cause the interpreter to treat it as a local, even if it was never assigned to. Annotations for local variables will not be evaluated:

However, if it is at a module or class level, then the type will be evaluated:

In addition, at the module or class level, if the item being annotated is a simple name , then it and the annotation will be stored in the __annotations__ attribute of that module or class (mangled if private) as an ordered mapping from names to evaluated annotations. Here is an example:

__annotations__ is writable, so this is permitted:

But attempting to update __annotations__ to something other than an ordered mapping may result in a TypeError:

(Note that the assignment to __annotations__ , which is the culprit, is accepted by the Python interpreter without questioning it – but the subsequent type annotation expects it to be a MutableMapping and will fail.)

The recommended way of getting annotations at runtime is by using typing.get_type_hints function; as with all dunder attributes, any undocumented use of __annotations__ is subject to breakage without warning:

Note that if annotations are not found statically, then the __annotations__ dictionary is not created at all. Also the value of having annotations available locally does not offset the cost of having to create and populate the annotations dictionary on every function call. Therefore, annotations at function level are not evaluated and not stored.

While Python with this PEP will not object to:

since it will not care about the type annotation beyond “it evaluates without raising”, a type checker that encounters it will flag it, unless disabled with # type: ignore or @no_type_check .

However, since Python won’t care what the “type” is, if the above snippet is at the global level or in a class, __annotations__ will include {'alice': 'well done', 'bob': 'what a shame'} .

These stored annotations might be used for other purposes, but with this PEP we explicitly recommend type hinting as the preferred use of annotations.

  • Should we introduce variable annotations at all? Variable annotations have already been around for almost two years in the form of type comments, sanctioned by PEP 484 . They are extensively used by third party type checkers (mypy, pytype, PyCharm, etc.) and by projects using the type checkers. However, the comment syntax has many downsides listed in Rationale. This PEP is not about the need for type annotations, it is about what should be the syntax for such annotations.
  • Introduce a new keyword: The choice of a good keyword is hard, e.g. it can’t be var because that is way too common a variable name, and it can’t be local if we want to use it for class variables or globals. Second, no matter what we choose, we’d still need a __future__ import.

The problem with this is that def means “define a function” to generations of Python programmers (and tools!), and using it also to define variables does not increase clarity. (Though this is of course subjective.)

  • Use function based syntax : It was proposed to annotate types of variables using var = cast(annotation[, value]) . Although this syntax alleviates some problems with type comments like absence of the annotation in AST, it does not solve other problems such as readability and it introduces possible runtime overhead.

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.

  • Parenthesized form (var: type) for annotations: It was brought up on python-ideas as a remedy for the above-mentioned ambiguity, but it was rejected since such syntax would be hairy, the benefits are slight, and the readability would be poor.

it is ambiguous, what should the types of y and z be? Also the second line is difficult to parse.

  • Allow annotations in with and for statement: This was rejected because in for it would make it hard to spot the actual iterable, and in with it would confuse the CPython’s LL(1) parser.
  • Evaluate local annotations at function definition time: This has been rejected by Guido because the placement of the annotation strongly suggests that it’s in the same scope as the surrounding code.
  • Store variable annotations also in function scope: The value of having the annotations available locally is just not enough to significantly offset the cost of creating and populating the dictionary on each function call.
  • Initialize variables annotated without assignment: It was proposed on python-ideas to initialize x in x: int to None or to an additional special constant like Javascript’s undefined . However, adding yet another singleton value to the language would needed to be checked for everywhere in the code. Therefore, Guido just said plain “No” to this.
  • Add also InstanceVar to the typing module: This is redundant because instance variables are way more common than class variables. The more common usage deserves to be the default.
  • Allow instance variable annotations only in methods: The problem is that many __init__ methods do a lot of things besides initializing instance variables, and it would be harder (for a human) to find all the instance variable annotations. And sometimes __init__ is factored into more helper methods so it’s even harder to chase them down. Putting the instance variable annotations together in the class makes it easier to find them, and helps a first-time reader of the code.
  • Use syntax x: class t = v for class variables: This would require a more complicated parser and the class keyword would confuse simple-minded syntax highlighters. Anyway we need to have ClassVar store class variables to __annotations__ , so a simpler syntax was chosen.
  • Forget about ClassVar altogether: This was proposed since mypy seems to be getting along fine without a way to distinguish between class and instance variables. But a type checker can do useful things with the extra information, for example flag accidental assignments to a class variable via the instance (which would create an instance variable shadowing the class variable). It could also flag instance variables with mutable defaults, a well-known hazard.
  • Use ClassAttr instead of ClassVar : The main reason why ClassVar is better is following: many things are class attributes, e.g. methods, descriptors, etc. But only specific attributes are conceptually class variables (or maybe constants).
  • Do not evaluate annotations, treat them as strings: This would be inconsistent with the behavior of function annotations that are always evaluated. Although this might be reconsidered in future, it was decided in PEP 484 that this would have to be a separate PEP.
  • Annotate variable types in class docstring: Many projects already use various docstring conventions, often without much consistency and generally without conforming to the PEP 484 annotation syntax yet. Also this would require a special sophisticated parser. This, in turn, would defeat the purpose of the PEP – collaborating with the third party type checking tools.
  • Implement __annotations__ as a descriptor: This was proposed to prohibit setting __annotations__ to something non-dictionary or non-None. Guido has rejected this idea as unnecessary; instead a TypeError will be raised if an attempt is made to update __annotations__ when it is anything other than a mapping.

the name slef should be evaluated, just so that if it is not defined (as is likely in this example :-), the error will be caught at runtime. This is more in line with what happens when there is an initial value, and thus is expected to lead to fewer surprises. (Also note that if the target was self.name (this time correctly spelled :-), an optimizing compiler has no obligation to evaluate self as long as it can prove that it will definitely be defined.)

This PEP is fully backwards compatible.

An implementation for Python 3.6 is found on GitHub repo at https://github.com/ilevkivskyi/cpython/tree/pep-526

This document has been placed in the public domain.

Source: https://github.com/python/peps/blob/main/peps/pep-0526.rst

Last modified: 2023-09-09 17:39:29 GMT

IMAGES

  1. Tuple Assignment in Python

    python tuple variable assignment

  2. Python tuple()

    python tuple variable assignment

  3. The Ultimate Guide to Python Tuples

    python tuple variable assignment

  4. Python List Of Tuples With 6 Examples

    python tuple variable assignment

  5. Working with Tuples in Python

    python tuple variable assignment

  6. Working with Tuples in Python

    python tuple variable assignment

VIDEO

  1. Tuple and multiple variable in Python . #python

  2. Lesson 1 Subprograms

  3. TUPLES AND TUPLE ASSIGNMENT IN PYTHON / Explained in Tamil and English

  4. multiple assignment in python

  5. #24

  6. What are Python Strings?

COMMENTS

  1. python: multiple variables using tuple

    The way you used the tuple was only to assign the single values to single variables in one line. This doesn't store the tuple anywhere, so you'll be left with 4 variables with 4 different values. When you change the value of country, you change the value of this single variable, not of the tuple, as string variables are "call by value" in python.

  2. Python's tuple Data Type: A Deep Dive With Examples

    In Python, a tuple is a built-in data type that allows you to create immutable sequences of values. The values or items in a tuple can be of any type. ... assigning an empty pair of parentheses to a variable is okay. The tuple() ... Parallel assignment is another cool use case of tuple unpacking. For example, say that you often do something ...

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

  4. 11.3. Tuple Assignment

    Tuple Assignment — Python for Everybody - Interactive. 11.3. Tuple Assignment ¶. One of the unique syntactic features of Python is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when the left side is a sequence. In this example we have a two-element list ...

  5. Lists and Tuples in Python

    Python Tuples. Python provides another type that is an ordered collection of objects, called a tuple. ... Tuple assignment allows for a curious bit of idiomatic Python. Frequently when programming, you have two variables whose values you need to swap. In most programming languages, it is necessary to store one of the values in a temporary ...

  6. 10.28. Tuple Assignment

    10.28. Tuple Assignment ¶. Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an assignment to be assigned values from a tuple on the right of the assignment. This does the equivalent of seven assignment statements, all on one easy line. One requirement is that the number of variables on the ...

  7. 9. Tuples

    Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an assignment to be assigned values from a tuple on the right of the assignment. (We already saw this used for pairs, but it generalizes.) (name, surname, b_year, movie, m_year, profession, b_place) = julia.

  8. Guide to Tuples in Python

    # Unpack a tuple into variables my_tuple = (1, 2, 3) a, b, c = my_tuple print (a) # Output: 1 print (b) # Output: 2 print (c) # Output: 3 Tuple Methods. In addition to the basic operations that you can perform on tuples, there are also several built-in methods that are available for working with tuples in Python.

  9. 10.3: Tuple Assignment

    This page titled 10.3: Tuple Assignment is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Chuck Severance. One of the unique syntactic features of the Python language is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when ….

  10. 5 Best Ways to Assign A Python Tuple to Two Variables

    Direct unpacking is the simplest and most straightforward way to assign elements of a tuple to two variables. Python supports unpacking iterables into individual variables directly. Here's an example: point = (10, 20) x, y = point. Output: x = 10 y = 20. This method sets variable x to the first element of the tuple and y to the second with a ...

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

  12. Tuples in Python

    It is called the variable "Packing." In Python, we can create a tuple by packing a group of variables. Packing can be used when we want to collect multiple values in a single variable. Generally, this operation is referred to as tuple packing. Similarly, we can unpack the items by just assigning the tuple items to the same number of variables.

  13. Python Tuple (With Examples)

    In Python, we use tuples to store multiple data similar to a list. ... Python Fundamentals. Python Variables, Constants and Literals; Python Type Conversion; Python Basic Input and Output ... (fruits) # Output: TypeError: 'tuple' object does not support item assignment. Delete Tuples We cannot delete individual items of a tuple. However, we can ...

  14. 5 Best Ways to Assign Python Tuple to Multiple Variables

    💡 Problem Formulation: In Python, developers often need to assign the elements of a tuple to separate variables in a clean and readable way. This task is common when dealing with function returns or data structures that inherently group multiple items, for example, (('apple', 'banana', 'cherry')).The desired output is having each fruit assigned to its own variable, like fruit1 = 'apple ...

  15. Tuple Assignment Python [With Examples]

    Here are some examples of tuple assignment in Python: Example 1: Basic Tuple Assignment. # Creating a tuple. coordinates = ( 3, 4 ) # Unpacking the tuple into two variables. x, y = coordinates. # Now, x is 3, and y is 4 Code language: Python (python) Example 2: Multiple Variables Assigned at Once. # Creating a tuple.

  16. Tuples in Python

    Creating Python Tuples. ... in the above snippet we are considering a variable called values which holds a tuple that consists of either int or str, the '…' means that the tuple will hold more than one int or str. ... line 11, in tuple1[1] = 100 TypeError: 'tuple' object does not support item assignment Accessing Values in Python Tuples ...

  17. Multiple assignment and tuple unpacking improve Python code readability

    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.

  18. Tuples

    Tuple Assignment# Python allows us to have a tuple on the left side of an assignment. In this way, we can assign more than one variable at a time. We usually omit the use of parentheses on the left side of an assignment statement. my_list : list = ['Data', 'Science'] a, b = my_list print(a) print(b) ...

  19. python

    Example 1 (Swapping) Tuple assignment can be very handy in order to swap the contents of variables. The following example shows how we can swap the contents of two elements in an array in a clear an concise way without the need of temporary variables:

  20. 13.3. Tuple Assignment with Unpacking

    Another way to think of this is that the tuple of values is unpacked into the variable names. Activity: 13.3.1 ActiveCode (ac12_4_1) 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.

  21. Python's Assignment Operator: Write Robust Assignments

    Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal—or an expression that evaluates to a value. To execute an assignment statement like the above, Python runs the following steps: Evaluate the right-hand expression to produce a concrete value or object.

  22. Multiple Assignment Syntax in Python

    The multiple assignment syntax, often referred to as tuple unpacking or extended unpacking, is a powerful feature in Python. There are several ways to assign multiple values to variables at once. Let's start with a first example that uses extended unpacking. This syntax is used to assign values from an iterable (in this case, a string) to ...

  23. python

    A tuple does not allow assignment but can be hashed. On the other hand, lists allow assignment but cannot be hashed. ... Python - 'tuple' object does not support item assignment. 2. Assign two variables from list of tuples in one iteration. 0. Work with tuples. 238. Python add item to the tuple. 1 (Python) Tuple/List Assignment. 0.

  24. Python Tuples

    Tuple. Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.. A tuple is a collection which is ordered and unchangeable.. Tuples are written with round brackets.

  25. Variables and data types

    The following four data types are the most basic in Python: 'Hello World!'. Function print() is a built-in function in Python that is used to print the specified message to the screen. The following examples show how to use the print() function. To show the data type of a variable, use the type() function. Cast a variable to a different data ...

  26. PEP 526

    Note that, although the syntax does allow tuple packing, it does not allow one to annotate the types of variables when tuple unpacking is used: ... Initialize variables annotated without assignment: It was proposed on python-ideas to initialize x in x: int to None or to an additional special constant like Javascript's undefined. However ...