'How do I assign variable names to every variables in my tuple? [duplicate]

I am trying to assign a name to every variable in a tuple. So my tuple is:

grid_defs = ((-0.073, 0.073, 4e-4), (-0.071, 0.075, 4e-4), (-0.065, 0.004, 4e-4))

and I want to give every number a variable name like this:

grid_defs = ((gx0, gx1, gxs), (gy0, gy1, gys), (gz0, gz1, gzs))

How can I do this?



Solution 1:[1]

You just have the assignment backwards. You want to unpack the value of grid_defs into a tuple-like target.

((gx0, gx1, gxs), (gy0, gy1, gys), (gz0, gz1, gzs)) = grid_defs

Solution 2:[2]

You should look at namedtuples. This data structure will allow you to create tuples and refer to their values by name, which may be what you want. You may also want to consider using a dictionary instead of a tuple depending on your specific use case.

If what you actually want is to unpack an existing tuple then you should see this answer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chepner
Solution 2 inteoryx