-1

Is it ok to assign variables like this in Python?:

mean, variance, std = 0

  • Those aren't declarations. It's an attempt at an assignment. You want this: `a = b = c = 0`. Just replace the commas with `=`. – Tom Karzes Nov 04 '21 at 17:55
  • 1
    Terminology note: python *doesn't have variable declarations* (although, you can kind of think of type annotations as declarations). This is a variable *definition*. In any case, what do you mean by "OK"? – juanpa.arrivillaga Nov 04 '21 at 17:55
  • @juanpa.arrivillaga Python has two types of variable declarations: `global` and `nonlocal`. That doesn't apply here, but it's worth noting. – Tom Karzes Nov 04 '21 at 17:57
  • @TomKarzes sort of, I wouldn't consider those variable *declarations*, they do not *create a variable*, they are directives that tell the compiler what scope the variable has. – juanpa.arrivillaga Nov 04 '21 at 17:59
  • Or: `mean, variance, std, max, min, sum = (0,)*6` – RufusVS Nov 04 '21 at 18:05
  • @juanpa.arrivillaga Declarations don't necessarily create variables. They declare them. For example, in C there are external declarations that declare externally defined variables. In any case, here's a direct quote from the Python documentation: "The global statement is a declaration which holds for the entire current code block." So they refer to it as a declaration. – Tom Karzes Nov 04 '21 at 18:07

2 Answers2

2

There are a few options for one-liners:

This version is only safe if assigning immutable object values like int, str, and float. Don't use this with mutable objects like list and dict objects.

mean = variance = std = max = min = sum = 0

Another option is a bit more verbose and does not have issues with mutable objects. You can raise ValueError errors if you don't have the same number of objects on each side.

mean, variance, std, max, min, sum = 0, 0, 0, 0, 0, 0
Registered User
  • 8,357
  • 8
  • 49
  • 65
  • Or: `mean, variance, std, max, min, sum = (0,)*6` – RufusVS Nov 04 '21 at 18:05
  • Instead of `a, b, c = 0, 0, 0` you could do `a = 0; b = 0; c = 0`. I don't see a particular advantage to cramming it all on one line though, unless the value really is guaranteed to be the same, in which case `a = b = c = 0` does make sense. – Tom Karzes Nov 05 '21 at 14:53
0

Did you try it?

>>> mean, variance, std, max, min, sum = 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

It must be:

mean = variance = std = max_ = min_ = sum_ = 0

Unless you have a deal with int, bool it is ok.

You can check it easily:

>>> id(mean) == id(variance)
True
>>> id(mean) == id(variance)
True
>>> mean = 1
>>> id(mean) == id(variance)
False

But:

>>> mean = variance = std = max_ = min_ = sum_ = {}
>>> mean['a'] = '1'
>>> variance['a']
'1'
>>> del mean['a']
>>> variance
{}
>>>

They all are the same. And please don't use sum, min, max as var names - it is a reserved word in Python.

mrvol
  • 2,575
  • 18
  • 21