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

Matthias Braun's user avatar

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.

Ondrej Tucny's user avatar

You can technically do this with a single statement, rather than two statements, using the following syntax, although the character count is almost identical.

Servy's user avatar

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:

Community's user avatar

Yes it is possible in C#. You'll need to install the package Value.Tuple in your project. You can do like this

Max's user avatar

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.

Ale Miralles's user avatar

This is what I do:

Jason Brown'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 c# tuples or ask your own question .

Hot Network Questions

python assign tuple to two variables

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

Chris Bailey

Lists and Tuples in Python Christopher Bailey 05:17

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.

python assign tuple to two variables

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

python assign tuple to two variables

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

python assign tuple to two variables

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.

python assign tuple to two variables

python assign tuple to two variables

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?

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?

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!

python assign tuple to two variables

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.

IMAGES

  1. How To Add Two Variables In Python

    python assign tuple to two variables

  2. Python Variables

    python assign tuple to two variables

  3. Python Tutorials

    python assign tuple to two variables

  4. Audio Programming In Python: 9. Python Tuples

    python assign tuple to two variables

  5. Python Variables: Declare, Concatenate, Global & Local

    python assign tuple to two variables

  6. Working with Tuples in Python

    python assign tuple to two variables

VIDEO

  1. 06

  2. Data Structure in Python (This part: TUPLE in Python)

  3. multiple variable assignments in Python

  4. SWAP TWO VARIABLES USING TUPLE PACKING AND TUPLE UNPACKING /WRITING BASIC PYTHON SCRIPTS/PART V

  5. (Tip 6) Python Added A New Way To Assign With Walruses

  6. Join Two Tuple In Python || #python #pythontutorial #shorts #youtubeshorts

COMMENTS

  1. python: multiple variables using tuple

    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

  2. Possible to initialize multiple variables from a tuple?

    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

  3. Tuple Assignment, Packing, and Unpacking

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

  4. 11.3. Tuple Assignment

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

  5. Python Assign Values to Multiple Variables

    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 »