Nat Gillin
Nat Gillin

Reputation: 253

Is there a skip parameter in Julia's range?

In Python, we could iterate using a for-loop and skip the indices using the skip parameter as such:

max_num, jump = 100, 10
for i in range(0, max_num, jump):
    print (i)

I could achieve the same with a while loop by doing this:

max_num, jump = 100, 10
i = 0
while i < max_num
    print(i)
    i+=jump
end

And using the same i+=jump syntax shown below in the for-loop doesn't skip the index:

for i in range(0,max_num)
    print(i)
    i+=jump
end

Within a for-loop is "skipping" possible? If so, how?

Upvotes: 4

Views: 1319

Answers (4)

Chris Rackauckas
Chris Rackauckas

Reputation: 19152

start:jump:end

Example:

a = 0:10:100

You can loop using that:

for a in 0:10:100
  println(a)
end

Upvotes: 1

ymonad
ymonad

Reputation: 12100

The syntax is a little bit different in Julia.

It's range(start, [step,]length) , e.g.

for i in range(0, 3, 10)
   println(i)
end

[out]:

0
3
6
9
12
15
18
21
24
27

There's another syntax start:step:max_num see @Sayse 's answer for detali

Upvotes: 3

Toterich
Toterich

Reputation: 585

You can just do

max_num, step = 100, 10

for i in 0:step:max_num
    println(i)
end

Using range(), you do not specify max_num, but the desired number of iterations. So 0:step:max_num equals range(0, step, max_num/step).

Upvotes: 9

Sayse
Sayse

Reputation: 43320

You do it in your first snipppet (define it in the range). Aside from that you'd have to use a modulo

for i in range(0,max_num):
    if(i % jump != 0):
        continue
    print(i)

Upvotes: 1

Related Questions