note.nkmk.me

Multiple assignment in python: assign multiple values or the same value to multiple variables.

In Python, use the = operator to assign values to variables.

You can assign values to multiple variables on one line.

This article describes the following two cases.

Assign multiple values to multiple variables

Assign the same value to multiple variables.

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

You can assign to more than three variables. It is also possible to assign to different types.

If there is one variable on the left side, it is assigned as a tuple.

If the number of variables on the left and the number of values on the right do not match, a ValueError will occur, but you can assign the rest as a list by appending * to the variable name.

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

It is also possible to swap the values of multiple variables in the same way. See the article below.

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

This is useful, for example, when initializing multiple variables to the same value.

It is also possible to assign another value into one after assigning the same value. As described later, care must be taken when assigning mutable objects such as lists or dictionaries.

Even three or more can be written in the same way.

Be careful when assigning mutable objects such as list or dict instead of immutable objects such as int , float , or str .

If you use = consecutively, the same object is assigned to all variables, so if you change the value of element or add a new element, the other will also change.

Same as below.

If you want to handle them separately, you need to assign them to each.

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.8.0 documentation

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

Related Categories

Related articles.

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Python assigning multiple variables to same value? list behavior

I tried to use multiple assignment as show below to initialize variables, but I got confused by the behavior, I expect to reassign the values list separately, I mean b[0] and c[0] equal 0 as before.

Result is: [1, 3, 5] [1, 3, 5] [1, 3, 5]

Is that correct? what should I use for multiple assignment? what is different from this?

result: ('f:', 3) ('e:', 4)

Marco's user avatar

13 Answers 13

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.

Names don't have any of that. Values do, of course, and you can have lots of names for the same value.

If you give Notorious B.I.G. a hot dog,* Biggie Smalls and Chris Wallace have a hot dog. If you change the first element of a to 1, the first elements of b and c are 1.

If you want to know if two names are naming the same object, use the is operator:

You then ask:

what is different from this?

Here, you're rebinding the name e to the value 4 . That doesn't affect the names d and f in any way.

In your previous version, you were assigning to a[0] , not to a . So, from the point of view of a[0] , you're rebinding a[0] , but from the point of view of a , you're changing it in-place.

You can use the id function, which gives you some unique number representing the identity of an object, to see exactly which object is which even when is can't help:

Notice that a[0] has changed from 4297261120 to 4297261216—it's now a name for a different value. And b[0] is also now a name for that same new value. That's because a and b are still naming the same object.

Under the covers, a[0]=1 is actually calling a method on the list object. (It's equivalent to a.__setitem__(0, 1) .) So, it's not really rebinding anything at all. It's like calling my_object.set_something(1) . Sure, likely the object is rebinding an instance attribute in order to implement this method, but that's not what's important; what's important is that you're not assigning anything, you're just mutating the object. And it's the same with a[0]=1 .

user570826 asked:

What if we have, a = b = c = 10

That's exactly the same situation as a = b = c = [1, 2, 3] : you have three names for the same value.

But in this case, the value is an int , and int s are immutable. In either case, you can rebind a to a different value (e.g., a = "Now I'm a string!" ), but the won't affect the original value, which b and c will still be names for. The difference is that with a list, you can change the value [1, 2, 3] into [1, 2, 3, 4] by doing, e.g., a.append(4) ; since that's actually changing the value that b and c are names for, b will now b [1, 2, 3, 4] . There's no way to change the value 10 into anything else. 10 is 10 forever, just like Claudia the vampire is 5 forever (at least until she's replaced by Kirsten Dunst).

* Warning: Do not give Notorious B.I.G. a hot dog. Gangsta rap zombies should never be fed after midnight.

abarnert's user avatar

Cough cough

Jimmy Kane's user avatar

In python, everything is an object, also "simple" variables types (int, float, etc..).

When you changes a variable value, you actually changes it's pointer , and if you compares between two variables it's compares their pointers . (To be clear, pointer is the address in physical computer memory where a variable is stored).

As a result, when you changes an inner variable value, you changes it's value in the memory and it's affects all the variables that point to this address.

For your example, when you do:

This means that a and b points to the same address in memory that contains the value 5, but when you do:

It's not affect b because a is now points to another memory location that contains 6 and b still points to the memory address that contains 5.

But, when you do:

a and b, again, points to the same location but the difference is that if you change the one of the list values:

It's changes the value of the memory that a is points on, but a is still points to the same address as b, and as a result, b changes as well.

Ori Seri's user avatar

Yes, that's the expected behavior. a, b and c are all set as labels for the same list. If you want three different lists, you need to assign them individually. You can either repeat the explicit list, or use one of the numerous ways to copy a list:

Assignment statements in Python do not copy objects - they bind the name to an object, and an object can have as many labels as you set. In your first edit, changing a[0], you're updating one element of the single list that a, b, and c all refer to. In your second, changing e, you're switching e to be a label for a different object (4 instead of 3).

HoldOffHunger's user avatar

You can use id(name) to check if two names represent the same object:

Lists are mutable; it means you can change the value in place without creating a new object. However, it depends on how you change the value:

If you assign a new list to a , then its id will change, so it won't affect b and c 's values:

Integers are immutable, so you cannot change the value without creating a new object:

tyteen4a03's user avatar

in your first example a = b = c = [1, 2, 3] you are really saying:

If you want to set 'a' equal to 1, 'b' equal to '2' and 'c' equal to 3, try this:

Hope this helps!

Nick Burns's user avatar

What you need is this:

pydsigner's user avatar

Simply put, in the first case, you are assigning multiple names to a list . Only one copy of list is created in memory and all names refer to that location. So changing the list using any of the names will actually modify the list in memory.

In the second case, multiple copies of same value are created in memory. So each copy is independent of one another.

Vikas's user avatar

The code that does what I need could be this:

Nathan Arthur's user avatar

To assign multiple variables same value I prefer list

Initialize multiple objects:

devp's user avatar

E.g: basically a = b = 10 means both a and b are pointing to 10 in the memory, you can test by id(a) and id(b) which comes out exactly equal to a is b as True .

is matches the memory location but not its value, however == matches the value.

let's suppose, you want to update the value of a from 10 to 5 , since the memory location was pointing to the same memory location you will experience the value of b will also be pointing to 5 because of the initial declaration.

The conclusion is to use this only if you know the consequences otherwise simply use , separated assignment like a, b = 10, 10 and won't face the above-explained consequences on updating any of the values because of different memory locations.

Muhammad Ghufran Azim's user avatar

The behavior is correct. However, all the variables will share the same reference. Please note the behavior below:

So, yes, it is different in the sense that if you assign a, b and c differently on a separate line, changing one will not change the others.

Yigit Alparslan's user avatar

Here are two codes for you to choose one:

My Car's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged python list or ask your own question .

Hot Network Questions

how to assign multiple variables same value in python

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

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 started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get your certification today!

how to assign multiple variables same value in python

Get certified by completing a course today!

Subscribe

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Your Suggestion:

Thank you for helping us.

Your message has been sent to W3Schools.

Top Tutorials

Top references, top examples, web certificates, get certified.

How to Initialize Multiple Variables to the Same Value in Python?

Summary: To initialize multiple variables to the same value in Python you can use one of the following approaches:

This article will guide you through the ways of assigning multiple variables with the same value in Python. Without further delay, let us dive into the solutions right away.

Method 1: Using Chained Equalities

You can use chained equalities to declare the variables and then assign them the required value.

It is evident from the above output that each variable has been assigned the same value and each of them point to the same memory location.

Method 2: Using dict.fromkeys

Approach: Use the dict.fromkeys(variable_list, val) method to set a specific value ( val ) to a list of variables ( variable_list ).

Discussion: It is evident from the above output that each variable assigned holds the same value. However, each variable occupies a different memory location. This is on account that each variable acts as a key of the dictionary and every key in a dictionary is unique. Thus, changes to a particular variable will not affect another variable as shown below:

Conceptual Read:

fromkeys() is a dictionary method that returns a dictionary based on specified keys and values passed within it as parameters. Syntax: dict.fromkeys(keys, value) ➡ keys is a required parameter that represents an iterable containing the keys of the new dictionary. ➡ value is an optional parameter that represents the values for all the keys in the new dictionary. By default, it is None .

Related Question

Let’s address a frequently asked question that troubles many coders.

Problem: I tried to use multiple assignment as show below to initialize variables, but I got confused by the behavior, I expect to reassign the values list separately, I mean b[0] and c[0] equal 0 as before.

But, why does the following assignment lead to a different behaviour?

Question Source: StackOverflow

Remember that everything in Python is treated as an object. So, when you chain multiple variables as in the above case all of them refer to the same object. This means, a , b and c are not different variables with same values rather they are different names given to the same object.

how to assign multiple variables same value in python

Thus, in the first case when you make a change at a certain index of variable a, i.e, a[0] = 1. This means you are making the changes to the same object that also has the names b and c. Thus the changes are reflected for b and c both along with a.

Verification:

To create a new object and assign it, you must use the copy module as shown below:

However, in the second case you are rebinding a different value to the variable a . This means, you are changing it in-place and that leads to a now pointing at a completely different value at a different location. Here, the value being changed is an interger and integers are immutable.

Follow the given illustration to visualize what’s happening in this case:

It is evident that after rebinding a new value to the variable a , it points to a different memory location, hence it now refers to a different object. Thus, changing the value of a in this case means we are creating a new object without touching the previously created object that was being referred by a , b and c .

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners   will teach you how to read and write “one-liners”:  concise statements of useful functionality packed into a single line of code.  You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce  key computer science concepts  and  boost your coding and analytical skills . You’ll learn about advanced Python features such as  list comprehension ,  slicing ,  lambda functions ,  regular expressions ,  map  and  reduce  functions, and  slice assignments .

You’ll also learn how to:

By the end of the book, you’ll know how to  write Python at its most refined , and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

shubham finxter profile image

I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.

You can contact me @:

UpWork LinkedIn

Related Tutorials

Related Articles

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. 

  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. 

Please Login to comment...

how to assign multiple variables same value in python

Improve your Coding Skills with Practice

Start your coding journey now.

Data Structure

How do we assign a value to several variables simultaneously in Python?

Python is not a "statically typed" programming language. We do not need to define variables or their types before utilizing them. Once we initially assign a value to a variable, it is said to be created. Each variable is assigned with a memory location.

The assignment operator (=) assigns the value provided to right to the variable name which is at its left.

The syntax of the assignment operator is shown below.

The following is the example which shows the usage of the assignment operator.

In Python, variable is really a label or identifier given to object stored in memory. Hence, same object can be identified by more than one variables.

a, b and c are three variables all referring to same object. This can be verified by id() function.

Python also allows different values to be assigned to different variables in one statement. Values from a tuple object are unpacked to be assigned to multiple variables.

Assigning values to several variables simultaneously.

Python assigns values in a left to right manner. Different variable names are provided to the left of the assignment operator, separated by a comma, when assigning multiple variables in a single line. The same is true for their values, except that they should be placed to the right of the assignment operator.

When declaring variables in this way, it's important to pay attention to the sequence in which the names and values are assigned. For example, the first variable name to the left of the assignment operator is assigned with the first value to the right, and so on.

Assigning homogenous data type at once

When all of the data elements in a structure are of the same data type, the structure is said to be homogenous. A single data type is shared by all the data items of a homogenous set. For instance: Arrays

In this example we will see how to assign a homogenous data type to variables in a single statement.

On executing the above code, the following output is obtained.

Assigning heterogeneous data types

Multiple types of data can be stored simultaneously in heterogeneous data structures.

In this example we will see how to assign a heterogenous data type to variables in a single statement.

Pranav Indukuri

0 Followers

Tutorials Point

Python: Check whether multiple variables have the same value

Python basic: exercise-124 with solution.

Write a Python program to check whether multiple variables have the same value.

Pictorial Presentation:

Check whether multiple variables have the same value

Sample Solution-1:

Python Code:

Sample Output:

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Sample Solution-2:

Flowchart: Check whether multiple variables have the same value.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to determine the largest and smallest integers, longs, floats. Next: Write a Python program to sum of all counts in a collections.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Simplify if statement:

IMAGES

  1. Python Variable (Assign value, string Display, multiple Variables & Rules)

    how to assign multiple variables same value in python

  2. Python Variables

    how to assign multiple variables same value in python

  3. Variable Assignment in Python

    how to assign multiple variables same value in python

  4. Python : Working with variables • Dot Net For All

    how to assign multiple variables same value in python

  5. Python Variables

    how to assign multiple variables same value in python

  6. Python Environment Setup and Essentials Tutorial

    how to assign multiple variables same value in python

VIDEO

  1. 06

  2. Easy way to assign multiple Variables from a List in Python

  3. multiple variable assignments in Python

  4. 1.Introduction to Variables in VB

  5. Leetcode Weekly Contest 332

  6. MS Forms to Planner

COMMENTS

  1. Assign multiple values or the same value to multiple variables

    You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables

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

    The difference is that with a list, you can change the value [1, 2, 3] into [1, 2, 3, 4] by doing, e.g., a.append(4) ; since that's actually

  3. Python Assign Values to Multiple Variables

    Python Assign Values to Multiple Variables ; ❮ Python Glossary ; ExampleGet your own Python Server. x, y, z = "Orange", "Banana", "Cherry" print(x) print(y)

  4. How to Initialize Multiple Variables to the Same Value in Python?

    It is evident from the above output that each variable has

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

  6. Python

    Method #1 : Using list comprehension By using list comprehension one can achieve this task with ease and in one line. · Method #2 : Using

  7. How do we assign a value to several variables simultaneously in

    Python assigns values in a left to right manner. Different variable names are provided to the left of the assignment operator, separated by a

  8. Assigning Multiple Values to Multiple Variables

    In this Video you will learn how you can assign one value or same value to multiple variables in Python.

  9. #11 Python Tutorial for Beginners

    In this video Assigning multiple variables in one line in Python is shown with easy examples. This video will assist you if you have any of

  10. How to assign the same value to multiple variables in the Python

    You can do it in two ways, either assign in each separate line, one var at a time,like a=10 b=10 x=10 or you can store each var in another var and assign a

  11. Python: Check whether multiple variables have the same value

    x = 20 y = 20 z = 20 if x == y == z == 20: print("All variables have same value!") Sample Output: All variables have same value! Visualize