Search code examples
pythonvariables

Assign variables in one line in Python


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

mean, variance, std = 0


Solution

  • 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