On Sun, Apr 3, 2016 at 4:12 AM, Jonatan Pallesen <[email protected]> wrote: > I want to make a list comprehension for 1 <= i < j <= 4. It can be done with > a for loop like this: > > l = [] > for i in 1:4, j in i+1:4 > push!(l, (i,j)) > end > > In python a list comprehension can be made like this > > l = [(i, j) for i in range(1, 5) for j in range(i+1, 5)] > > But this Julia code gives an error, saying i is not defined: > > l = [(i,j) for i in 1:4, j in i+1:4] > > Is there another approach? I feel like 4 lines to do this is excessive
Since `i` and `j` are integers, you probably want to initialize the output array with `Int[]`. This will improve performance. In Python, a comprehension yields a one-dimensional array, hence ragged loop boundaries are possible. In Julia, this syntax gives you a two-dimensional array, hence the loop ranges cannot depend on each other. The reason things were designed that way is that, in Python, a list (a one-dimensional array) is the "natural" data structure, whereas in Julia, a multi-dimensional array is "natural". Currently, the for loop you showed is the best way to do this. There is a discussion about generators and appropriate syntax on the development mailing list, but this isn't ready for testing yet. The `vcat` solution suggested below is slower since it creates several intermediate arrays and then concatenates them; this might or might not be important to you. -erik -- Erik Schnetter <[email protected]> http://www.perimeterinstitute.ca/personal/eschnetter/
