5

It is possible to assign values to multiple variables.

a, b = 5, 10

I need to assign those values based on a condition and I tried,

a, b = 1, 1 if c == 1 else 5, 10

It resulted a ValueError.

ValueError: too many values to unpack

I tried with two conditions for each and it was a success.

a, b = 1 if c == 1 else 5, 1 if c == 1 else 10

But I need to achieve this using a single if condition, single line. I know this reduces the readability. But still is it possible? What am I doing wrong here?

1
  • 1
    Just out of interest, why do you need to do this? Commented Jul 16, 2015 at 11:33

4 Answers 4

21

You can acheive this by putting (a, b) in parentheses.

a, b = (1, 1) if c == 1 else (5, 10)

The current code is equivalent to

a, b = 1, (1 if c == 1 else 5), 10

Which gives a value error as you are trying to unpack a 3-tuple into two variables.

Sign up to request clarification or add additional context in comments.

Comments

6

You could also index based using the result of c == 1:

a, b = ((5, 10), (1, 1))[c == 1]

The result of c == 1 will either be True -> 1 or False -> 0 so we will end up taking (1, 1) i.e index 1 if the condition evaluates to True or (5, 10) i.e 0 if it is False.

Comments

2

Try this:

a, b = ((a, b) if c == 1 else (5, 10))

or this

a, b = (a, b) if c == 1 else (5, 10)

Comments

1

If you are dealing with vectors, you can also use numpy.

import numpy as np
condition = np.arange(10) > 5
x = np.ones(10)
y = np.zeros(10)

(a,b) = np.where(condition, (x,y), (y,x))

print(a)
[0. 0. 0. 0. 0. 0. 1. 1. 1. 1.]
print(b) 
[1. 1. 1. 1. 1. 1. 0. 0. 0. 0.]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.