# How to pick out selected output components of a named tuple?

I have a function `f() = (a=1, b=2, c=3) `, and I can pick out one of the returned components of the tuple as

``````julia> f().a
1
``````

Can I select in this way `a` and at the same time `c`? In other words, I would like to get `a, c = f()???`.

2 Likes

You could do `(; a, c) = f()`

4 Likes

Ah, that is very good. Thanks!

Only works for Julia \geq 1.7 though

1 Like

Actually, I realized I would really like to be able to collect the results in variables whose names are not the same as those in the named tuple. For example: `myvar = f().c`. But with an arbitrary multiple selection, `myv1, myv2 = f()...` (let us say, `a` and `c`).

Can this be done?

OK, found this:

``````julia> v1, v2 = f()[[:a, :c]]
(a = 1, c = 3)

julia> v1
1

julia> v2
3
``````

Can this be made more succinct?

3 Likes
``````julia> f() = (; a=1, b=2, c=3, d=4)
f (generic function with 1 method)

julia> x, _, _, y = f()
(a = 1, b = 2, c = 3, d = 4)

julia> x
1

julia> y
4
``````
1 Like

here there may be something close

1 Like
1 Like

Nice! What I’m not so happy about is that one has to know the order in which the arguments have been returned.

How do you want it to look? There’s not all that much unsuccinctness to work with in the solution you found.

1 Like

If this is the best, I shall be content. Don’t blame @PetrKryslUCSD. Like all good Julians, he’s greedy .

1 Like

This looks good, could avoid allocating that array of symbols because named tuples support indexing with tuples of symbols `f()[(:a, :c)]`.

3 Likes