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

In Python, the = operator is used to assign values to variables.

You can assign values to multiple variables in one line.

Assign multiple values to multiple variables

Assign the same value to multiple variables.

You can assign multiple values to multiple variables by separating them with commas , .

You can assign values to more than three variables, and it is also possible to assign values of different data types to those variables.

When only one variable is on the left side, values on the right side are assigned as a tuple to that variable.

If the number of variables on the left does not match the number of values on the right, a ValueError occurs. You can assign the remaining values as a list by prefixing the variable name with * .

For more information on using * and assigning elements of a tuple and list to multiple variables, see the following article.

  • Unpack a tuple and list in Python

You can also swap the values of multiple variables in the same way. See the following article for details:

  • Swap values ​​in a list or values of variables in Python

You can assign the same value to multiple variables by using = consecutively.

For example, this is useful when initializing multiple variables with the same value.

After assigning the same value, you can assign a different value to one of these variables. As described later, be cautious when assigning mutable objects such as list and dict .

You can apply the same method when assigning the same value to three or more variables.

Be careful when assigning mutable objects such as list and dict .

If you use = consecutively, the same object is assigned to all variables. Therefore, if you change the value of an element or add a new element in one variable, the changes will be reflected in the others as well.

If you want to handle mutable objects separately, you need to assign them individually.

after c = []; d = [] , c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d .) 3. Data model — Python 3.11.3 documentation

You can also use copy() or deepcopy() from the copy module to make shallow and deep copies. See the following article.

  • Shallow and deep copy in Python: copy(), deepcopy()

Related Categories

Related articles.

  • NumPy: arange() and linspace() to generate evenly spaced values
  • Chained comparison (a < x < b) in Python
  • pandas: Get first/last n rows of DataFrame with head() and tail()
  • pandas: Filter rows/columns by labels with filter()
  • Get the filename, directory, extension from a path string in Python
  • Sign function in Python (sign/signum/sgn, copysign)
  • How to flatten a list of lists in Python
  • None in Python
  • Create calendar as text, HTML, list in Python
  • NumPy: Insert elements, rows, and columns into an array with np.insert()
  • Shuffle a list, string, tuple in Python (random.shuffle, sample)
  • Add and update an item in a dictionary in Python
  • Cartesian product of lists in Python (itertools.product)
  • Remove a substring from a string in Python
  • pandas: Extract rows that contain specific strings from a DataFrame

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.

Mastering Multiple Variable Assignment in Python

Python's ability to assign multiple variables in a single line is a feature that exemplifies the language's emphasis on readability and efficiency. In this detailed blog post, we'll explore the nuances of assigning multiple variables in Python, a technique that not only simplifies code but also enhances its readability and maintainability.

Introduction to Multiple Variable Assignment

Python allows the assignment of multiple variables simultaneously. This feature is not only a syntactic sugar but a powerful tool that can make your code more Pythonic.

What is Multiple Variable Assignment?

  • Simultaneous Assignment : Python enables the initialization of several variables in a single line, thereby reducing the number of lines of code and making it more readable.
  • Versatility : This feature can be used with various data types and is particularly useful for unpacking sequences.

Basic Multiple Variable Assignment

The simplest form of multiple variable assignment in Python involves assigning single values to multiple variables in one line.

Syntax and Examples

Parallel Assignment : Assign values to several variables in parallel.

  • Clarity and Brevity : This form of assignment is clear and concise.
  • Efficiency : Reduces the need for multiple lines when initializing several variables.

Unpacking Sequences into Variables

Python takes multiple variable assignment a step further with unpacking, allowing the assignment of sequences to individual variables.

Unpacking Lists and Tuples

Direct Unpacking : If you have a list or tuple, you can unpack its elements into individual variables.

Unpacking Strings

Character Assignment : You can also unpack strings into variables with each character assigned to one variable.

Using Underscore for Unwanted Values

When unpacking, you may not always need all the values. Python allows the use of the underscore ( _ ) as a placeholder for unwanted values.

Ignoring Unnecessary Values

Discarding Values : Use _ for values you don't intend to use.

Swapping Variables Efficiently

Multiple variable assignment can be used for an elegant and efficient way to swap the values of two variables.

Swapping Variables

No Temporary Variable Needed : Swap values without the need for an additional temporary variable.

Advanced Unpacking Techniques

Python provides even more advanced ways to handle multiple variable assignments, especially useful with longer sequences.

Extended Unpacking

Using Asterisk ( * ): Python 3 introduced a syntax for extended unpacking where you can use * to collect multiple values.

Best Practices and Common Pitfalls

While multiple variable assignment is a powerful feature, it should be used judiciously.

  • Readability : Ensure that your use of multiple variable assignments enhances, rather than detracts from, readability.
  • Matching Lengths : Be cautious of the sequence length. The number of elements must match the number of variables being assigned.

Multiple variable assignment in Python is a testament to the language’s design philosophy of simplicity and elegance. By understanding and effectively utilizing this feature, you can write more concise, readable, and Pythonic code. Whether unpacking sequences or swapping values, multiple variable assignment is a technique that can significantly improve the efficiency of your Python programming.

Python Many Values to Multiple Variables

Answered on: Sunday 30 July, 2023 / Duration: 20 min read

Programming Language: Python , Popularity : 7/10

Python Programming on www.codeease.net

Solution 1:

In Python, you can assign multiple values to multiple variables in a single line of code. This is often referred to as "unpacking" or "multiple assignment." The number of variables on the left side of the assignment operator ( = ) should match the number of values on the right side, which can be a tuple, list, or any other iterable.

Here's an example of how to use multiple assignment in Python:

Output of Example 1:

Output of Example 2:

Output of Example 3:

Output of Example 4:

Output of Example 5:

Multiple assignment is a convenient feature in Python that allows you to assign values to multiple variables in a concise and readable manner. It is particularly useful when dealing with functions that return multiple values, iterating over collections, or handling various data structures.

Solution 2:

In Python, it is possible to assign multiple values to multiple variables in a single line using the concept of tuple assignment. This is also known as "packing" or "unpacking".

Here is an example:

In this example, we have assigned three values (1, 2, and 3) to three variables (a, b, and c) in a single line. The comma separates the values and the equals sign assigns them to the corresponding variables.

It is also possible to assign a single value to multiple variables by using a tuple:

This way, we can assign a single value to two or more variables.

Additionally, it's also possible to assign multiple values to a single variable, like this:

It's important to note that when assigning multiple values to multiple variables, the number of values must match the number of variables. Also, it's not possible to assign less values than the number of variables, if so, it will raise a SyntaxError.

It's also worth mentioning that this feature of Python is called "tuple packing" and it's a concise way of assigning multiple values to multiple variables in one step. It makes the code more readable and easier to write.

Please let me know if there is anything else I can assist you with.

Solution 3:

In Python, you can assign multiple variables at once. This is often called "unpacking" and it works with any iterable object. This feature allows values to be unpacked directly into variables in a way that is often more convenient, readable, and efficient than accessing them through indices or calling next() on an iterator.

Here is a simple example:

In this example, we have a list values with three values. We can assign these values to three variables ( name , age , and major ) in a single line. The first value in the list (which is "Alice") is assigned to the first variable ( name ), the second value is assigned to the second variable, and so on.

Note that the number of variables must match the number of values, or else Python will raise a ValueError . This is true for other iterables as well:

Python also provides a method to assign the same value to several variables at once:

In this case, the integer 0 is assigned to all three variables ( x , y , and z ).

More Articles :

Python beautifulsoup requests.

Answered on: Sunday 30 July, 2023 / Duration: 5-10 min read

Programming Language : Python , Popularity : 9/10

pandas add days to date

Programming Language : Python , Popularity : 4/10

get index in foreach py

Programming Language : Python , Popularity : 10/10

pandas see all columns

Programming Language : Python , Popularity : 7/10

column to list pyspark

How to save python list to file.

Programming Language : Python , Popularity : 6/10

tqdm pandas apply in notebook

Name 'cross_val_score' is not defined, drop last row pandas, tkinter python may not be configured for tk.

Programming Language : Python , Popularity : 8/10

translate sentences in python

Python get file size in mb, how to talk to girls, typeerror: argument of type 'windowspath' is not iterable, django model naming convention, split string into array every n characters python, print pandas version, python randomly shuffle rows of pandas dataframe, display maximum columns pandas.

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.

kushal-study-logo

What is Multiple Assignment in Python and How to use it?

multiple-assignment-in-python

When working with Python , you’ll often come across scenarios where you need to assign values to multiple variables simultaneously.

Python provides an elegant solution for this through its support for multiple assignments. This feature allows you to assign values to multiple variables in a single line, making your code cleaner, more concise, and easier to read.

In this blog, we’ll explore the concept of multiple assignments in Python and delve into its various use cases.

Understanding Multiple Assignment

Multiple assignment in Python is the process of assigning values to multiple variables in a single statement. Instead of writing individual assignment statements for each variable, you can group them together using a single line of code.

In this example, the variables x , y , and z are assigned the values 10, 20, and 30, respectively. The values are separated by commas, and they correspond to the variables in the same order.

Simultaneous Assignment

Multiple assignment takes advantage of simultaneous assignment. This means that the values on the right side of the assignment are evaluated before any variables are assigned. This avoids potential issues when variables depend on each other.

In this snippet, the values of x and y are swapped using multiple assignments. The right-hand side y, x evaluates to (10, 5) before assigning to x and y, respectively.

Unpacking Sequences

One of the most powerful applications of multiple assignments is unpacking sequences like lists, tuples, and strings. You can assign the individual elements of a sequence to multiple variables in a single line.

In this example, the tuple (3, 4) is unpacked into the variables x and y . The value 3 is assigned to x , and the value 4 is assigned to y .

Multiple Return Values

Functions in Python can return multiple values, which are often returned as tuples. With multiple assignments, you can easily capture these return values.

Here, the function get_coordinates() returns a tuple (5, 10), which is then unpacked into the variables x and y .

Swapping Values

We’ve already seen how multiple assignments can be used to swap the values of two variables. This is a concise way to achieve value swapping without using a temporary variable.

Iterating through Sequences

Multiple assignment is particularly useful when iterating through sequences. It allows you to iterate over pairs of elements in a sequence effortlessly.

In this loop, each tuple (x, y) in the points list is unpacked and the values are assigned to the variables x and y for each iteration.

Discarding Values

Sometimes you might not be interested in all the values from an iterable. Python allows you to use an underscore (_) to discard unwanted values.

In this example, only the value 10 from the tuple is assigned to x , while the value 20 is discarded.

Multiple assignments is a powerful feature in Python that makes code more concise and readable. It allows you to assign values to multiple variables in a single line, swap values without a temporary variable, unpack sequences effortlessly, and work with functions that return multiple values. By mastering multiple assignments, you’ll enhance your ability to write clean, efficient, and elegant Python code.

Related: How input() function Work in Python?

python multiple assignments at once

Vilashkumar is a Python developer with expertise in Django, Flask, API development, and API Integration. He builds web applications and works as a freelance developer. He is also an automation script/bot developer building scripts in Python, VBA, and JavaScript.

Related Posts

How to Scrape Email and Phone Number from Any Website with Python

How to Scrape Email and Phone Number from Any Website with Python

How to Build Multi-Threaded Web Scraper in Python

How to Build Multi-Threaded Web Scraper in Python

How to Search and Locate Elements in Selenium Python

How to Search and Locate Elements in Selenium Python

CRUD Operation using AJAX in Django Application

CRUD Operation using AJAX in Django Application

Leave a comment cancel reply.

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

Save my name, email, and website in this browser for the next time I comment.

Sign up on Python Hint

Join our community of friendly folks discovering and sharing the latest topics in tech.

We'll never post to any of your accounts without your permission.

Multiple assignment semantics

on 11 months ago

Unpacking tuples in Python

Using the star operator (*) in multiple assignments, swapping variables with multiple assignment, conclusion:, port matlab bounding ellipsoid code to python.

31453 views

10 months ago

How to debug Django unit tests?

47357 views

9 months ago

Iterate over individual bytes in Python 3

49546 views

11 months ago

How do I use OpenCV MatchTemplate?

64851 views

svg diagrams using python

55294 views

Related Posts

Assigning list to one value in that list

Python: anything wrong with dynamically assigning instance methods as instance attributes, what is happening when i assign a list with self references to a list copy with the slice syntax `mylist[:] = [mylist, mylist, ...]`, why give a local variable an initial value immediately before assigning to it, automatically echo the result of an assignment statement in ipython, how to assign random values from a list to a column in a pandas dataframe, understanding python variable assignment, how to assign columns while ignoring index alignment, python del() built-in can't be used in assignment, how does python assign values after assignment operator, python assigning two variables on one line, numpy assigning to slice, when is the array copied, how to use a python list to assign a std::vector in c++ using swig, assigning (yield) to a variable, how to create groups and assign permission during project setup in django, installation.

Copyright 2023 - Python Hint

Term of Service

Privacy Policy

Cookie Policy

Metric Coders

  • Apr 9, 2023

Assigning multiple variables at once in Python

Updated: Apr 19, 2023

python multiple assignments at once

We can assign values to multiple variables by passing comma separated values as shown below:

If the same value needs to assigned to several variables, we can do it the following way:

If the values present in a list needs to be assigned one by one to different variables, we can do so in the following way.

The link to the Github repository is here .

  • machine-learning-tutorials

Related Posts

Text Classification with scikit-learn: A Beginner's Guide

In today's data-driven world, the ability to analyze and categorize text data is invaluable. Text classification, a fundamental task in natural language processing (NLP), involves automatically assign

Keras Tutorials

Breast Cancer Classification using Gaussian Process and Scikit-Learn

Introduction: Machine learning continues to revolutionize the landscape of healthcare, aiding in the early detection and diagnosis of diseases. In this blog post, we'll embark on a journey through a P

Assigning Multiple Values At Once

Here's a cool programming shortcut: in Python, you can use a tuple to assign multiple values at once.

>>> v = ('a', 2, True) >>> (x, y, z) = v ®

I. v is a tuple of three elements, and (x, y, z) is a tuple of three variables. Assigning one to the other assigns each of the values of v to each of the variables, in order.

This has all kinds of uses. Suppose you want to assign names to a range of values. You can use the built-in range() function with multi-variable assignment to quickly assign consecutive values.

>>> (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7) ® >>> MONDAY ®

1. The built-in range() function constructs a sequence of integers. (Technically, the range() function returns an iterator, not a list or a tuple, but you'll learn about that distinction later.) MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are the variables you're defining. (This example came from the calendar module, a fun little module that prints calendars, like the UNIX program cal. The calendar module defines integer constants for days of the week.)

2. Now each variable has its value: MONDAY is 0, TUESDAY is 1, and so forth.

You can also use multi-variable assignment to build functions that return multiple values, simply by returning a tuple of all the values. The caller can treat it as a single tuple, or it can assign the values to individual variables. Many standard Python libraries do this, including the os module, which you'll learn about in the next chapter.

Continue reading here: Compound Field Names

Was this article helpful?

Related Posts

  • O Installing on Mac OS X - Python Tutorial
  • Lambda functions that take a tuple instead of multiple
  • Relative imports within a package
  • Basestring datatype - Python Tutorial
  • Halt And Catch Fire - Python Tutorial
  • Serializing Datatypes Unsupported by json

livingwithcode logo

  • Python Guide

Assign Multiple Variables in Python

By James L.

In this article, we will discuss the following topics:

Assign the same value to multiple variables

  • Assign multiple values to multiple variables (Tuple Unpacking)

We can assign the same value to multiple variables in Python by using the assignment operator ( = ) consecutively between the variable names and assigning a single value at the end.

For example:

a = b = c = 200

The above code is equivalent to 

In the above example, all three variables a , b , and c are assigned a value of 200 .

If we have assigned the same value to multiple variables in one line, then we must be very careful when modifying or updating any of the variables.

Lots of beginners get this wrong. Keep in mind that everything in Python is an object and some objects in Python are mutable and some are immutable.

Immutable objects are objects whose value cannot be changed or modified after they have been assigned a value.

Mutable objects are objects whose value can be changed or modified even after they have been assigned a value.

For immutable objects like numeric types (int, float, bool, and complex), str, and tuple, if we update the value of any of the variables, it will not affect others.

In the above example, I initially assigned a value of 200 to all three variables a , b , and c . Later I changed the value of variable b to 500 . When I printed all three variables, we can see that only the value of variable b is changed to 500 while the values of variables a and c are still 200 .

Note : In Python, immutable data types and immutable objects are the same. Also, mutable data types and mutable objects are the same. This may not be the case in other programming languages.

For mutable objects like list, dict, and set, if we update the value of any one of the variables. The value of other variables also gets changed.

In the above example, I initially assigned [1, 2, 3, 4] to all three lists a , b , and c . Later I appended a value of 10 to the list b . When I print all three lists to the console, we can see that the value of 10 is not just appended to list b , it is appended to all three lists a , b , and c .

Assigning the same value of mutable data types to multiple variables in a single line may not be a good idea. The whole purpose of having a mutable object in Python is so that we can update the values. 

If you are sure that you won’t be updating the values of mutable data types, then you can assign values of mutable data types to multiple variables in a single line. Otherwise, you should assign them separately.

a = [1, 2, 3, 4]

b = [1, 2, 3, 4]

c = [1, 2, 3, 4]

The value of immutable objects cannot be changed doesn’t mean the variable assigned with an immutable object cannot be reassigned to a different value. It simply means the value cannot be changed but the same variable can be assigned a new value. 

We can see this behavior of an object by printing the id of the object by using the id() function. The id is the memory address of the object. In Python, all objects have a unique id.

The ID of immutable object:

In the above example, I initially assigned a value of 100 to variable a . When I printed the id of variable a to the console, it is 1686573813072 . Later I changed the value of a to 200 . Now when I print the id of variable a , it is 1686573816272 . Since the id of variable a in the beginning and after I changed the value is different, we can conclude that variable a was pointing to a different memory address in the beginning and now it is pointing to a different memory address. It means that the previous object with its value is replaced by the new object with its new value.

Note : The id will be different from my output id for your machine. May even change every time you run the program.

The ID of mutable object:

In the above example, I have assigned [1, 2, 3, 4] to list a . When I printed the id of list a , it is 1767333244416 . Later, I appended a value of 10 to the list a . When I print the id of the list a , it is still 1767333244416 . Since the id of the list a in the beginning and after I appended a value is the same, we can conclude that list a is still pointing to the same memory address. This means that the value of list a is modified. 

Assign multiple variables to the multiple values (Tuple Unpacking)

In Python, we can assign multiple values separated by commas to multiple variables separated by commas in one line using the assignment operator ( = ) .

a, b, c = 100, 200, 300

In the above example, variable a is assigned a value of 100 , variable b is assigned a value of 200 , and variable c is assigned a value of 300 respectively.

We have to make sure that the number of variables is equal to the number of values. Otherwise, it will throw an error.

We can also assign values of different data types to multiple variables in one line.

a, b, c = 2.5, 400, "Hello World"

In the above example, variable a is assigned a value of float data type, variable b is assigned a value of integer data type, and c is assigned a value of string data type.

If the number of values is more than the number of variables, we can still assign those values to multiple variables by placing an asterisk (*) before the variable.

Notice the variable with an asterisk (*) is assigned a list.

This method of assigning multiple variables to multiple values is also called tuple unpacking. In the above examples, what we are doing is, we are unpacking the elements of a tuple and assigning them to multiple separate variables.

In Python, we can create tuples with or without parenthesis.

E.g. a = 1, 2, 3 and a = (1, 2, 3) both are the same thing.

Our first example of assigning multiple variables to multiple values can also be written as:

We can also assign tuples to multiple variables directly.

a, b, c = (100, 200, 300)

We can also unpack other iterable objects like lists, sets, and dictionaries.

Related Posts

Latest posts.

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 assign values to multiple variables, assign value to multiple variables.

Python allows you to assign values to multiple variables in one line:

And you can assign the same value to multiple variables in one line:

Related Pages

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.

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Python | Check if all elements in list follow a condition
  • Python - Swap elements in String list
  • Python program to print all Strong numbers in given list
  • Python Program to get K length groups with given summation
  • Python - Remove non-increasing elements
  • Python - Consecutive Ranges of K greater than N
  • Add custom borders to matrix in Python
  • Python - Remove duplicate words from Strings in List
  • Python - First Even Number in List
  • Python - Merge consecutive empty Strings
  • Python program to create a list centered on zero
  • Python - Pairs with Sum equal to K in tuple list
  • Python - Occurrence counter in List of Records
  • Python - Construct variables of list elements
  • Python - Group similar value list to dictionary
  • Python - Remove Record if Nth Column is K
  • Python - Incremental Range Initialization in Matrix
  • Python - Remove empty List from List
  • Python - Summation in Dual element Records List

Python | Assign multiple variables with list values

We generally come through the task of getting certain index values and assigning variables out of them. The general approach we follow is to extract each list element by its index and then assign it to variables. This approach requires more line of code. Let’s discuss certain ways to do this task in compact manner to improve readability. 

Method #1 : Using list comprehension By using list comprehension one can achieve this task with ease and in one line. We run a loop for specific indices in RHS and assign them to the required variables. 

Time Complexity: O(n), where n is the length of the input list. This is because we’re using list comprehension which has a time complexity of O(n) in the worst case. Auxiliary Space: O(1), as we’re using additional space res other than the input list itself with the same size of input list.

  Method #2 : Using itemgetter() itemgetter function can also be used to perform this particular task. This function accepts the index values and the container it is working on and assigns to the variables.   

  Method #3 : Using itertools.compress() compress function accepts boolean values corresponding to each index as True if it has to be assigned to the variable and False it is not to be used in the variable assignment. 

Method #4:  Using dictionary unpacking

using dictionary unpacking. We can create a dictionary with keys corresponding to the variables and values corresponding to the indices we want, and then unpack the dictionary using dictionary unpacking.

1. Create a list with the given values. 2. Create a dictionary with keys corresponding to the variables and values corresponding to the indices we want. 3. Unpack the dictionary using dictionary unpacking.

Time Complexity: O(1) Space Complexity: O(k), where k is the number of variables

Please Login to comment...

Similar reads.

author

  • Python list-programs
  • What are Tiktok AI Avatars?
  • Poe Introduces A Price-per-message Revenue Model For AI Bot Creators
  • Truecaller For Web Now Available For Android Users In India
  • Google Introduces New AI-powered Vids App
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Multiple Assignments in Python

    python multiple assignments at once

  2. Variables and Assignments

    python multiple assignments at once

  3. 02 Multiple assignments in python

    python multiple assignments at once

  4. Multiple Assignments in Python[P04] #multiple assignments in single

    python multiple assignments at once

  5. Python Basics 4

    python multiple assignments at once

  6. Lists

    python multiple assignments at once

VIDEO

  1. 6.1 Multiple assignments

  2. Python Basics

  3. Daily Python

  4. Multiple assignments in Python #coding #codingtips #python

  5. Assignment

  6. 2024 Python

COMMENTS

  1. Multiple assignment in Python: Assign multiple values or the same value

    Unpack a tuple and list in Python; You can also swap the values of multiple variables in the same way. See the following article for details: Swap values in a list or values of variables in Python; Assign the same value to multiple variables. You can assign the same value to multiple variables by using = consecutively.

  2. Python Multiple Assignment Statements In One Line

    All credit goes to @MarkDickinson, who answered this in a comment: Notice the + in (target_list "=")+, which means one or more copies.In foo = bar = 5, there are two (target_list "=") productions, and the expression_list part is just 5. All target_list productions (i.e. things that look like foo =) in an assignment statement get assigned, from left to right, to the expression_list on the right ...

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

  4. Assigning multiple variables in one line in Python

    Python assigns values from right to left. When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should be to the right of the assignment operator. While declaring variables in this fashion one ...

  5. Multiple Assignments in Python

    Chain those equals signs!Python allows multiple assignments, or chained assignments, to assign multiple variables or expressions at once. This can be a usefu...

  6. Efficient Coding with Python: Mastering Multiple Variable Assignment

    Multiple variable assignment in Python is a testament to the language's design philosophy of simplicity and elegance. By understanding and effectively utilizing this feature, you can write more concise, readable, and Pythonic code. Whether unpacking sequences or swapping values, multiple variable assignment is a technique that can ...

  7. Python Variables

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  8. Python Many Values to Multiple Variables

    Solution 3: In Python, you can assign multiple variables at once. This is often called "unpacking" and it works with any iterable object. This feature allows values to be unpacked directly into variables in a way that is often more convenient, readable, and efficient than accessing them through indices or calling next() on an iterator.. Here is a simple example:

  9. Multiple assignment and tuple unpacking improve Python code readability

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

  10. Python assigning multiple variables to same value? list behavior

    If you're coming to Python from a language in the C/Java/etc. family, it may help you to stop thinking about a as a "variable", and start thinking of it as a "name".. a, b, and c aren't different variables with equal values; they're different names for the same identical value. Variables have types, identities, addresses, and all kinds of stuff like that.

  11. What is Multiple Assignment in Python and How to use it?

    Multiple assignment in Python is the process of assigning values to multiple variables in a single statement. Instead of writing individual assignment statements for each variable, you can group them together using a single line of code. In this example, the variables x, y, and z are assigned the values 10, 20, and 30, respectively.

  12. Multiple assignment semantics

    Multiple assignment semantics in Python refers to the ability to assign values to multiple variables in a single statement. This feature is a convenient way to assign values to multiple variables at once, and it is commonly used in many programming tasks. For example, we can assign values to multiple variables at once by separating the values ...

  13. Assigning multiple variables at once in Python

    This tutorial explains how to assign multiple values or variables at once in Python. We can assign values to multiple variables by passing comma separated values as shown below:a, b, c = 10, 20, "Hello World!" print(a) print(b) print(c) #printing multiple values print(a,b,c)If the same value needs to assigned to several variables, we can do it ...

  14. Simultaneous Assignment in Python

    This video is about simultaneous assignment in Python. It displays how to assign values to multiple variables at once. ------

  15. Multiple assignments into a python dictionary

    Running the same test (on M1), I get different results: 934 µs ± 9.61 µs per loop; 1.3 ms ± 23.8 µs per loop; 744 µs ± 1.3 µs per loop; 1.02 ms ± 2.17 µs per loop; 816 µs ± 955 ns per loop; 693 µs ± 1.51 µs per loop; You can improve update's performance by instantiating a dict in advance; d1.update(dict(zip(keys, values))) has the same runtime as {**d1, **dict)(zip(keys, values ...

  16. Assigning Multiple Values At Once

    Here's a cool programming shortcut: in Python, you can use a tuple to assign multiple values at once. >>> v = ('a', 2, True) >>> (x, y, z) = v ®. I. v is a tuple of three elements, and (x, y, z) is a tuple of three variables. Assigning one to the other assigns each of the values of v to each of the variables, in order. This has all kinds of uses.

  17. Assign Multiple Variables in Python

    We can assign the same value to multiple variables in Python by using the assignment operator (=) consecutively between the variable names and assigning a single value at the end. For example: a = b = c = 200. The above code is equivalent to . c = 200. b = c. a = b. In the above example, all three variables a, b, and c are assigned a value of ...

  18. Python Assign Values to Multiple Variables

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  19. python

    4. Python employs assignment unpacking when you have an iterable being assigned to multiple variables like above. In Python3.x this has been extended, as you can also unpack to a number of variables that is less than the length of the iterable using the star operator: >>> a,b,*c = [1,2,3,4] >>> a. 1. >>> b. 2.

  20. Python

    Method #4: Using dictionary unpacking Approach. using dictionary unpacking. We can create a dictionary with keys corresponding to the variables and values corresponding to the indices we want, and then unpack the dictionary using dictionary unpacking.

  21. Assigning to multiple columns at once (python pandas)

    So I have started a question yesterday: Multiple assignment in pandas based on the values in the same row, where I was wondering how to rank a row of data and assign the ranks to different columns in the same row.