Correct way to do multiple variable assignments

I am trying to find out the right way to do something like this:

a,b,c = 1,2,3

or perhaps

a,b,c = (1,2,3)

I am seeing that this thread says that the left hand side is actually being interpreted as

(a,b,c) = ...

so therefore

(a,b,c) = (1,2,3) 

is also valid. Is there a better way to do assignment like this, or are any of the above okay?

1 Like

Those all look fine to me, and they all do the same thing. The first one is probably the most common, but you should use whichever one makes your code easiest to read and understand (at least for you). In all cases you’re assigning a Tuple of items on the right-hand side of the = sign to a Tuple of variables on the left-hand side.

3 Likes

Hi, with a boolean cond I often write conditional assignment like

julia> cond = true
true

julia> cond && (a = 1)
1

but today I wrote a multiple assignment:

cond && (a, b = 1, 2)
ERROR: syntax: invalid named tuple element "2" around REPL[22]:1

Also I tried:

julia> cond && (a,b=[4,5])
(a = 1, b = [4, 5])

julia> a,b
(1, 2)

Sincerely, I’m a little lost with these named tuples:-(

Anything with commas inside parenthesis is interpreted as a tuple (or a named tuple if it contains =), so that’s why that does not work.

Instead of cond && (a, b = 1, 2) write:

julia> cond && begin a, b = 1, 2 end
(1, 2)

julia> a
1

julia> b
2
5 Likes

You can of course also add more parentheses:

julia> true && ((a,b) = (1,2))
(1, 2)

julia> a
1

julia> b
2
5 Likes

heliosdrm && pfitzseb && (many thanks)

1 Like