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.
- Unpack a tuple and list in Python
It is also possible to swap the values of multiple variables in the same way. See the article below.
- Swap values in a list or values of variables in Python
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.
- Shallow and deep copy in Python: copy(), deepcopy()
Related Categories
Related articles.
- Integer (int) has no max limit in Python3
- Chained comparison (a
- Save still images from camera video with OpenCV in Python
- Default arguments in Python
- Conditional expressions in Python
- Concatenate images with Python, Pillow
- List of built-in functions, constants, etc. in Python (dir(__builtins__))
- Pretty-print with pprint in Python
- Random sampling from a list in Python (random.choice, sample, choices)
- Replace strings in Python (replace, translate, re.sub, re.subn)
- NumPy: Ellipsis (...) for ndarray
- NumPy: Replace NaN (np.nan) in ndarray
- Binarize image with Python, NumPy, OpenCV
- String comparison in Python (exact/partial match, etc.)
- Get the n-largest/smallest elements from a list in Python
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
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)
- 3 Do you want a , b , and c, to all point to the same value (in this case a list), or do you want a=0 , b=3 , and c=5 . In that case, you want a,b,c = [0,3,5] or just a,b,c = 0,3,5 . – chepner May 2, 2013 at 22:52
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.
- What if we have, a = b = c = 10; and when we try to update the value of b, it does effect any other? although i checked their ids are the same.? – A.J. Aug 11, 2014 at 14:42
- 2 @user570826: 10 is immutable—that means there is no way to update the value, so your question doesn't make sense. You can point b at a different value, but doing so has no effect on a and c , which are still pointing at the original value. The difference that lists make is that they're mutable—e.g., you can append to a list, or lst[0] = 3 , and that will update the value, which will be visible through all names for that value. – abarnert Aug 11, 2014 at 17:43
- "If you give Notorious B.I.G. a hot dog,* Biggie Smalls and Chris Wallace have a hot dog." I don't know who these people are, could you use a different example, maybe something not so culture based? – Bassie-c Mar 5, 2022 at 21:50
- 1 @Bassie-c, this answer is from 2013. Most people coding at that time would have been old enough to know Notorious B.I.G. People to young to know Notorious B.I.G, are young enough to know Google. This means you must have born before the 70's or so. So let's try this: If you give the King of Rock and Roll a hot dog*, Elvis-the-Pelvis and E. A. Presley have a hot dog. * Don't worry, the King is still alive! So no need to worry if he is a zombie if you see him, and you can feed him all you want. – Lu Kas Sep 15, 2022 at 15:05
Cough cough
- 17 IMHO, this actually answers OP first key question of what should I use for multiple assignment, whereas the higher rated and more cerebral answer above doesn't. – Will Croxford Feb 13, 2019 at 11:08
- 7 Or a,b,c = 1,2,3 without brackets works in Python 2 or 3, if u really want that extra cm of readibility. – Will Croxford Sep 18, 2019 at 13:39
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.
- 6 This is highly misleading. Pointers are certainly not visible at the Python level, and at least two of the four major implementations (PyPy and Jython) don't use them even inside the implementation. – abarnert May 2, 2013 at 23:15
- 1 You welcome to read and explore python internals and you'll discover that every variable in python is actually pointer. – Ori Seri May 2, 2013 at 23:21
- 4 No. In one implementation of Python (CPython), every variable is a pointer to a PyObject . That's not true in other implementations like PyPy or Jython. (In fact, it's not even clear how it could be true, because the languages those implementations are written in don't even have pointers.) – abarnert May 2, 2013 at 23:29
- I think the use of "pointer" in a conceptual sense is ok (perhaps with a disclaimer that implementations may vary), esp if the goal is to convey behavior. – Levon Aug 5, 2015 at 14:47
- @abarnert When people say Python they mean CPython, not other rarely used implementations. Just like when people say Kleenex they mean facial tissue. Playing the semantics game in these comments is really unnecessary. As for what he wrote, is the behavior of what he described wrong? – swade Jul 17, 2018 at 18:44
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).
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:
- 1 id isn't necessarily a memory location. As the docs say, this returns the "identity… an integer… which is guaranteed to be unique and constant for this object during its lifetime." CPython happens to use the memory address as the id , but other Python implementations may not. PyPy, for example, doesn't. And saying "two vars point to the same memory location" is misleading to anyone who understands it C-style. "Two names for the same object" is both more accurate and less misleading. – abarnert May 2, 2013 at 23:18
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!
What you need is this:

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.

The code that does what I need could be this:
To assign multiple variables same value I prefer list
Initialize multiple objects:
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.
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.
Here are two codes for you to choose one:

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 .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- What is the point of Thrower's Bandolier?
- What can a lawyer do if the client wants him to be acquitted of everything despite serious evidence?
- better way to photograph a LED wall (people dancing in front of it)
- What is the correct way to screw wall and ceiling drywalls?
- What did Ctrl+NumLock do?
- How to follow the signal when reading the schematic?
- Finite abelian groups with fewer automorphisms than a subgroup
- Why is there a voltage on my HDMI and coaxial cables?
- Do I need a thermal expansion tank if I already have a pressure tank?
- Salesforce queuable implementation
- Is a PhD visitor considered as a visiting scholar?
- FAA Handbooks Copyrights
- Euler: “A baby on his lap, a cat on his back — that’s how he wrote his immortal works” (origin?)
- Transgenic Peach DNA Splicing
- Styling contours by colour and by line thickness in QGIS
- Is there a proper earth ground point in this switch box?
- Minimising the environmental effects of my dyson brain
- Knocking Out Zombies
- Short story taking place on a toroidal planet or moon involving flying
- How do particle accelerators like the LHC bend beams of particles?
- How to react to a student’s panic attack in an oral exam?
- Does a summoned creature play immediately after being summoned by a ready action?
- What video game is Charlie playing in Poker Face S01E07?
- Has 90% of ice around Antarctica disappeared in less than a decade?
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

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

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:
- Use chained equalities as: var_1 = var_2 = value
- Use dict.fromkeys
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.

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 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:
- Leverage data structures to solve real-world problems , like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array , shape , axis , type , broadcasting , advanced indexing , slicing , sorting , searching , aggregating , and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups , negative lookaheads , escaped characters , whitespaces, character sets (and negative characters sets ), and greedy/nongreedy operators
- Understand a wide range of computer science topics , including anagrams , palindromes , supersets , permutations , factorials , prime numbers , Fibonacci numbers, obfuscation , searching , and algorithmic sorting
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!!

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
- The Ultimate Guide to Python Lists
- Python One Line X
- 100 Code Puzzles to Train Your Rapid Python Understanding
- 56 Python One-Liners to Impress Your Friends
- Python Dictionary - The Ultimate Guide
- Python List of Lists - A Helpful Illustrated Guide to Nested…
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Android App Development with Kotlin(Live)
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- React JS (Basic to Advanced)
- JavaScript Foundation
- Complete Data Science Program(Live)
- Mastering Data Analytics
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Python – Assign values to Values List
Python | Assign multiple variables with list values
- Important differences between Python 2.x and Python 3.x with examples
- Python Keywords
- Keywords in Python | Set 2
- Namespaces and Scope in Python
- Statement, Indentation and Comment in Python
- How to assign values to variables in Python and other languages
- How to print without newline in Python?
- Python end parameter in print()
- Python | sep parameter in print()
- Python | Output Formatting
- Python String format() Method
- f-strings in Python
- Enumerate() in Python
- Iterate over a list in Python
- Print lists in Python (5 Different Ways)
- Twitter Interview Questions | Set 2
- Twitter Interview | Set 1
- Twitter Sentiment Analysis using Python
- Python | Sentiment Analysis using VADER
- Text Analysis in Python 3
- Python | NLP analysis of Restaurant reviews
- Tokenize text using NLTK in python
- Removing stop words with NLTK in Python
- Adding new column to existing DataFrame in Pandas
- Python map() function
- Read JSON file using Python
- How to get column names in Pandas dataframe
- Taking input in Python
- Difficulty Level : Expert
- Last Updated : 21 Jun, 2022
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...
- sagartomar9927
- Python list-programs
- Python Programs

Improve your Coding Skills with Practice
Start your coding journey now.
- Coding Ground
- Corporate Training
- Trending Categories

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
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.

0 Followers
- Related Articles
- How do we assign values to variables in Python?
- How do I assign a dictionary value to a variable in Python?
- How to assign values to variables in Python
- What do you mean MySQL user variables and how can we assign values to\nthem?
- Assign multiple variables to the same value in JavaScript?
- How to assign same value to multiple variables in single statement in C#?
- How to assign values to variables in C#?
- Assign multiple variables with a Python list values
- Can we assign a reference to a variable in Python?
- How can we assign a bit value as a number to a user variable?
- Assign ids to each unique value in a Python list
- Assign value to unique number in list in Python
- How can we assign a function to a variable in JavaScript?
- How to assign a value to a base R plot?
- Python - Assign a specific value to Non Max-Min elements in Tuple

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:

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:

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:
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises

IMAGES
VIDEO
COMMENTS
You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables
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
Python Assign Values to Multiple Variables ; ❮ Python Glossary ; ExampleGet your own Python Server. x, y, z = "Orange", "Banana", "Cherry" print(x) print(y)
It is evident from the above output that each variable has
Python assigns values from right to left. When assigning multiple variables in a single line, different variable names are provided to the left
Method #1 : Using list comprehension By using list comprehension one can achieve this task with ease and in one line. · Method #2 : Using
Python assigns values in a left to right manner. Different variable names are provided to the left of the assignment operator, separated by a
In this Video you will learn how you can assign one value or same value to multiple variables in Python.
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
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
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