Iterator from 3 vectors

Hi,
I’m trying to create an iterator that does the following:

vec_coord_x=[1,2,3]
vec_coord_y=[1,2,3]
vec_coord_z=[1,2,3]

[(x,y,z) for x in vec_coord_x for y in vec_coord_y for z in vec_coord_z]

Resulting in:
27-element Vector{Tuple{Int64, Int64, Int64}}:
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 2, 1)
(1, 2, 2)
(1, 2, 3)

(3, 2, 2)
(3, 2, 3)
(3, 3, 1)
(3, 3, 2)
(3, 3, 3)

I can use the for loop, but I think it would be faster with the iterator, correct?
Is there a function in the pack “IterTools” that do this?
Thank you!

The generator expression is optimal itself, just use parentheses rather than square brackets to avoid collecting the elements.

2 Likes

I think I found it, I was not just wording the search right.

it_1=Iterators.product(vec_coord_x,vec_coord_y,vec_coord_z)
for (a,b,c) in it_1
    println(a,b,c)
end

I’m told that Julia stands for “Just using loops is amazing” or something like that. :slight_smile: … although after many years of Python, I like iterators a lot.

1 Like

Hi!
I found the code Iterators.product(vec_coord_x,vec_coord_y,vec_coord_z) does that.
Do you think it would be better to change back to what I was using? Or is the same?
Thanks for the help!

In theory there shouldn’t be a big difference, but I won’t swear on it. If one is better performance it’s probably the product. But you can check by using BemchmarkTools; @btime your_function() with a function that creates the iterator and realistically uses elements from it.

2 Likes