1

Does anybody know whether Python can do the same thing as for i= 1:2:5 in Matlab? So i=1,3,5.

I know I can use other approaches to do this, but I want to know the equivalent form in Python.

jwodder
  • 54,758
  • 12
  • 108
  • 124
sjtupuzhao
  • 137
  • 1
  • 4

2 Answers2

4

try:

for i in xrange(1,6,2):
    print i

This print:

1
3
5

Use xrange instead of range if you are using python 2.x because it is more efficient as it generates an iterable object, and not the whole list.

Hasan Ramezani
  • 5,004
  • 24
  • 30
1

Use the range function:

for i in range(1, 6, 2):
    print(i)
Blair
  • 15,356
  • 7
  • 46
  • 56