Reputation: 3
Is it ok to assign variables like this in Python?
mean, variance, std = 0
Upvotes: -1
Views: 966
Reputation: 2983
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.
Upvotes: 0
Reputation: 8395
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
Upvotes: 2