12

I'm writing a function to calculate calendar dates. While cutting down on lines, I've found that I am unable to assign multiple variables to the same range.

Jan, Mar, May, Jul, Aug, Oct, Dec = range(1,32)

Would there be an efficient way to assign these values and why does python give a ValueError?

1

2 Answers 2

68

Use

Jan = Mar = May = ... = range(1, 32)
Sign up to request clarification or add additional context in comments.

7 Comments

I was typing out an answer just as you submitted yours, and then realized there is no way to give a better answer than the inventor of python :-)
@tijko: It does allow it. But the result of range(x) is trying to be unpacked into the variables on the left. This works: a,b = 1,2
@jdi: Thanks for the reply, I meant why is that multiple variables can't be assigned to the same range?
@tijko: I'm not sure if many languages would do that using the comma-separated syntax. I would guess in python, its because then it would break value unpacking functionality.
@jdi: Right after I re-phrased the question I read CrazyJugglerDrummers answer and it laid out a nice explanation. Thanks.
|
6

The easiest way to do what you described would be to use the x=y=z ... = VALUE syntax, where x, y, z, and any other variables you include will all be assigned the value of VALUE.

In your example, all the comma-separated variables on the left side of the equals sign are assigned to sequential values of a tuple on the right side. Hence, you could do something like this:

values = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec = values

In your code, you have 7 values on the left, and 31 on the right, so you get an out of range error because the list on the left is longer than the number or variables on the left side to be assigned the values in it. I know the code above doesn't have much relevance to achieving your goal, but I thought I'd at least give some insight as to what it was trying to do. :D

1 Comment

Thanks, that was exactly what I was wondering and makes perfect sense to my follow-up questions. So its fine to assign: a,b,c = range(3)

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.