Best way to generate vector of tuples based on two vectors

The following does what I want, generate a vector of tuples thanks to the two vectors that I provide.

xycoordinates = Tuple{Int,Int}[(x,y) for x in collect(1:10), y in rand(1:10, 10)]

I wanted to know if there exists a better way for doing this or is it already optimal, in terms of code readability and conciseness.

tuple.(x, y)? Though I think you are creating tuple.(x, y') in your example actually

2 Likes

Thanks! Plus there was a mistake in my code, I generated a matrix instead of a vector.

1 Like

A side remark: There are some unnecessary allocations in your code. You can just use 1:10 instead of collect(1:10). And rand(1:10, 10) also creates a vector that it not really needed.

Iā€™m not sure if you want a vector with 10 or with 100 elements as the result. In the first case you can say

[(x, rand(1:10)) for x in 1:10]

and in the second

[(x, rand(1:10)) for x in 1:10 for _ in 1:10]
2 Likes

Indeed, and also, the type annotation is redundant here (as also demonstrated by your example)

One can simply allow the comprehension to determine the type automatically.

1 Like