How to add several values for one index in a comprehension?

What would be the idiomatic way to get array like [1, -1, 2, -2, 3, -3] (or in general [f(idx1), g(idx1), f(idx2), g(idx2)] which have several values per one index following one another).

[(i,-i) for i in 1:5] gives a list of tuples, [(i,-i)... for i in 1:5] is not allowed, and [i,-i for i in 1:5] doesn’t work.

1 Like

EDIT: now I see what you were trying to do with ... … so … never mind. :slight_smile:

I’m not sure if I would call this idiomatic, but this works:

julia> collect(Iterators.flatten((i, -i) for i in 1:5 ))
10-element Vector{Int64}:
  1
 -1
  2
 -2
  3
 -3
  4
 -4
  5
 -5
3 Likes

If you really require two iterables f and g, zipping and flattening them works: collect(Iterators.flatten(zip(1:5, -1:-1:-5))).

If you can base it off one iterable 1:5, one-liners generally still involve flatten. You can actually pull this off with plain comprehension implementing nested loops with flatten: [sign*absval for absval in 1:5 for sign in (1, -1)].

v1.9 added Iterators.flatmap to write this a bit shorter (not sure why else): collect(Iterators.flatmap(i -> (i, -i), 1:5)). One of the documented examples is almost like this example.

tbh I would probably fill an uninitialized array in plain loops directly describing the sequence before I figure out the various one-liners for brevity and verify their type-inferrability.

2 Likes