- 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.
Possible to initialize multiple variables from a tuple?
In some languages (such as PHP, Haskell, or Scala), you can assign multiple variables from tuples in a way that resembles the following pseudocode:
I can't find a way to do this in C#, however, without writing longer, uglier code:
This two-line solution is obviously not the end of the world, but I'm always looking for ways to write prettier code.
Does anyone know a better way to do this?
- 5 You can't initialize multiple variables from tuple. And yes, tuples are ugly in C# – Sergey Berezovskiy Jan 2, 2014 at 22:19
- See also this duplicate question: stackoverflow.com/q/28261964/240733 – stakx - no longer contributing Feb 1, 2015 at 11:44
7 Answers 7
This is now available in C# 7:
You can even use a single var declaration:
More on destructuring tuples in the official documentation .
Valid up to C# 6:
No, this is not possible. There's no such language feature in C#.
If you think the following code:
is ugly, then you should reconsider using tuples at the first place.
UPDATE: As of C# 7, tuple deconstruction is now possible. See the documentation for more information.
See Jared's answer as well.
- I would add that "moving things around" is not something that you would do very frequently in C#. Unless you want to give the thing a shorter name, and use it many times in your code, you would probably access tupleWithTwoValues.Item1 directly instead of putting it in a variable. – Federico Berasategui Jan 2, 2014 at 22:27
- 2 True. Just seconds after posting that, it hit me that a richer solution (like a DTO) is often the way to go whenever I'm considering a tuple. – Micah Jan 2, 2014 at 22:30
- @Micah Yes, including semantics is always a plus. Tuples are usually a good thing in very specific scenarios only. – Ondrej Tucny Jan 2, 2014 at 22:32
- 1 This is now available in C#: learn.microsoft.com/en-us/dotnet/csharp/tuples#deconstruction – shmup Jun 27, 2017 at 12:56
- 2 @Jared Thanks for pointing that out. Updated my answer, although back in 2014 that language feature hadn't existed. – Ondrej Tucny Jun 27, 2017 at 21:57
You can technically do this with a single statement, rather than two statements, using the following syntax, although the character count is almost identical.
No this is not supported in C#, although others have suggested adding a feature like this ( here and here ).
It is supported by F#, however:
- It is now available in C#: learn.microsoft.com/en-us/dotnet/csharp/tuples#deconstruction – shmup Jun 27, 2017 at 12:56
Yes it is possible in C#. You'll need to install the package Value.Tuple in your project. You can do like this
when it comes to lists, you can do something like this:
(It's not that wordy) But for multiple variables, no. You can't do that.

This is what I do:
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 c# tuples 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
- How do I align things in the following tabular environment?
- Why do small African island nations perform better than African continental nations, considering democracy and human development?
- How to follow the signal when reading the schematic?
- The difference between the phonemes /p/ and /b/ in Japanese
- Who owns code in a GitHub organization?
- remove package from CTAN
- Knocking Out Zombies
- Why are physically impossible and logically impossible concepts considered separate in terms of probability?
- Largest Binary Area
- Where does this (supposedly) Gibson quote come from?
- Tips for golfing in SVG
- How to react to a student’s panic attack in an oral exam?
- How to handle a hobby that makes income in US
- Does a summoned creature play immediately after being summoned by a ready action?
- Did any DOS compatibility layers exist for any UNIX-like systems before DOS started to become outmoded?
- How do I connect these two faces together?
- Why is this sentence from The Great Gatsby grammatical?
- Follow Up: struct sockaddr storage initialization by network format-string
- Bulk update symbol size units from mm to map units in rule-based symbology
- Why zero amount transaction outputs are kept in Bitcoin Core chainstate database?
- Checking system vs. SEPA and the like
- Is there a solutiuon to add special characters from software and how to do it
- What's the difference between a power rail and a signal line?
- Counting Letters in a String
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 .
Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Tuple Assignment, Packing, and Unpacking

Lists and Tuples in Python Christopher Bailey 05:17
- Discussion (4)
In this lesson, you’ll learn about tuple assignment, packing, and unpacking. A literal tuple containing several items can be assigned to a single object. Assigning the packed object to a new tuple unpacks the individual items into the objects in the new tuple:
00:00 In this video, I’m going to show you tuple assignment through packing and unpacking. A literal tuple containing several items can be assigned to a single object, such as the example object here, t .
00:16 Assigning that packed object to a new tuple, unpacks the individual items into the objects in that new tuple. When unpacking, the number of variables on the left have to match the number of values that are inside of the tuple.
00:33 Let me have you explore that with some code. As you saw in the previous video, you can create a tuple just by typing the objects into the set of parentheses, and that will pack them all in there, into that single object. Again, you can access them via index.
00:56 Here’s an interesting idea. You can create another tuple of objects—in this case, (s1, s2, s3, s4) , and you could assign it to the tuple that you created a moment ago, t .
01:13 Now, s1 , s2 , s3 , and s4 will have unpacked that tuple during that assignment and placed them into the appropriate objects. It’s pretty neat!
01:27 Now, it’s important that they have the same number on both sides of that assignment. If you tried to assign it to (s1, s2, s3) = t , you are going to raise an exception here, a ValueError . There’s too many values to unpack.
01:41 It was expecting three on this side and t , as you know, has four. So again, here’s t . And what if you went with too many? Well, in this case, it was expecting to get five, but t only provided four. Packing and unpacking could be done into one statement if you wanted to.
02:12 And here they all are. Again, the two sides have to be equal.
02:23 Here, again, too many values. When doing assignments like this, there’s a handful of situations where Python’s going to allow you to skip the parentheses.
02:41 And the same with the unpacking.
02:50 You can even do something like this, where both sides don’t have parentheses.
03:02 Even creating that singleton. It works the same whether the parentheses are included or not, so if you have any doubt as to whether they’re needed, go ahead and include them.
03:14 This tuple assignment allows for a bit of idiomatic Python. Frequently when programming, you have two variables whose values you need to swap. In most programming languages, it’s necessary to store one of the values into a temporary variable while the swap occurs. It would look something like this.
03:48 So you create a variable temp , assign a into it, assign b into a , and then say b = temp . And there—you’ve swapped the two.
03:58 So again, you’re making a temporary variable that holds a , taking b , assigning it into a , and then b pulling that temp back into it by reassigning it again.
04:08 That’s the swap. But in Python, the swap can be done with just a single tuple assignment.
04:24 Here you’re going to say a, b = b, a . And you can see that the swap has occurred. It brings me to this kind of cool example that I saw from python.org. In teaching a little bit about programming they showed this example that I liked a lot about the Fibonacci series.
04:47 Here, we’re assigning the first two, 0 and 1 , and then creating a while loop. And then inside the while loop, you’re doing something very similar, just modifying it a little bit by assigning a on the left to b .
05:05 But you’re taking b and you’re saying that now equals a+b . Pretty neat! Next step is the conclusion and the course review.
reb24 on May 8, 2020
If I run this:
I can’t see any magic happening or reason to use temp variable to accomplish the swap

Dan Bader RP Team on May 8, 2020
The “magic” is that with Python you can do the swap without using an extra temporary variable. Many other programming languages would require the use of a temporary variable. Hope that clarifies it :)
Ah Ok !!! Thanks Dan
kiran on July 25, 2020
Multiple Assignment (n, m = 300, 400) also called Tuple packing & unpacking?
Source: Multiple Assignment
Become a Member to join the conversation.

- Runestone in social media: Follow @iRunestone Our Facebook Page
- Table of Contents
- Assignments
- Peer Instruction (Instructor)
- Peer Instruction (Student)
- Change Course
- Instructor's Page
- Progress Page
- Edit Profile
- Change Password
- Scratch ActiveCode
- Scratch Activecode
- Instructors Guide
- About Runestone
- Report A Problem
- Mixed-Up Code Questions
- Write Code Questions
- Peer Instruction: Tuples Multiple Choice Questions
- 11.1 Tuples are Immutable
- 11.2 Comparing Tuples
- 11.3 Tuple Assignment
- 11.4 Dictionaries and Tuples
- 11.5 Multiple Assignment with Dictionaries
- 11.6 The Most Common Words
- 11.7 Using Tuples as Keys in Dictionaries
- 11.8 Sequences: Strings, Lists, and Tuples - Oh My!
- 11.9 Debugging
- 11.10 Glossary
- 11.11 Multiple Choice Questions
- 11.12 Tuples Mixed-Up Code Questions
- 11.13 Write Code Questions
- 11.2. Comparing Tuples" data-toggle="tooltip">
- 11.4. Dictionaries and Tuples' data-toggle="tooltip" >

11.3. Tuple Assignment ¶
One of the unique syntactic features of Python is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when the left side is a sequence.
In this example we have a two-element list (which is a sequence) and assign the first and second elements of the sequence to the variables x and y in a single statement.
This isn’t magic! Python roughly translates the tuple assignment syntax to the following:
It’s worth noting that Python does not translate the syntax literally. For example, if you try this with a dictionary, it won’t work as you might expect.
Stylistically, when we use a tuple on the left side of the assignment statement, we omit the parentheses, but the following is an equally valid syntax:
11-9-4: What is associated with the variable ‘x’ once the following code is run?
- Incorrect! The values in random_list are strings, not lists. Try again.
- Incorrect! x is listed before y in the tuple on the left side of the assignment statement, so the first value in random_list should be assigned to x. Try again.
- Correct! This properly assigns the first element of the list to 'x'.
A particularly clever application of tuple assignment allows us to swap the values of two variables in a single statement:
Both sides of this statement are tuples, but Python interprets the left side to be a tuple of variables and the right side to be a tuple of expressions. All of the expressions on the right side are evaluated before any of the assignments. This means that the values of b and a on the right side are evaluated, then a and b on the left side take on their values.
The number of variables on the left and the number of values on the right must be the same:
Write code to swap the values of tuple t.
More generally, the right side can be any kind of sequence (string, list, or tuple). For example, to split an email address into a username and a domain, you could write:
The return value from split() is a list with two elements; the first element is assigned to uname , the second to domain .
11-9-6: What is associated with the variable ‘domain’ once the following code is run?
- hotmail.com
- Correct! The split() method splits the email address at '@'.
- @hotmail.com
- Incorrect! The split() method doesn't include its parameter in any of the elements of its returned list. Try again.
- ['hotmail.com']
- Incorrect! The split() method returns a list of strings, not a list of lists. Try again.
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.

IMAGES
VIDEO
COMMENTS
If you want to assign multiple variables at once, you can use tuples: name,age,country,career = ('Diana',32,'Canada','CompSci') print (country) I did this.. country = 'India' print (country) and it's modified. How come? python tuples Share Improve this question Follow edited Jun 4, 2020 at 17:59 John Kugelman 344k 67 521 569
You can technically do this with a single statement, rather than two statements, using the following syntax, although the character count is almost identical. string firstValue = tupleWithTwoValues.Item1 , secondValue = tupleWithTwoValues.Item2; Share Improve this answer Follow answered Jan 2, 2014 at 22:22 Servy 201k 26 326 439 Add a comment 1
Frequently when programming, you have two variables whose values you need to swap. In most programming languages, it’s necessary to store one of the values into a temporary variable while the swap occurs. It would look something like this. 03:48 So you create a variable temp, assign a into it, assign b into a, and then say b = temp. And there ...
Tuple Assignment — Python for Everybody - Interactive. 11.3. Tuple Assignment ¶. One of the unique syntactic features of Python is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when the left side is a sequence. In this example we have a two-element list ...
Assign Value to Multiple Variables Python allows you to assign values to multiple variables in one line: Example x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) Try it Yourself » And you can assign the same value to multiple variables in one line: Example x = y = z = "Orange" print(x) print(y) print(z) Try it Yourself »