0

I've been learning Python but I come from a background of Java and in Java, you can set the value that the iterator increases or decreases in each run through the loop. For example, you can say for(int i = 0; i < 10; i = i + 2) so that the iterator increases by two each time.

From what I've seen so far in Python tutorials, the for loop is unchanging and iterates through each integer from a beginning value to an end value, increasing by one each time. Is there a way to manipulate the Python for loop to set your own increase/decrease value for the iterator?

Jon Snow
  • 230
  • 1
  • 9
  • "the for loop is unchanging and iterates through each integer from a beginning value to an end value, increasing by one each time." No; it doesn't "iterate through integers" at all. It iterates through the **sequence** that you give to it. `range` is **not part of** the syntax of the `for` loop. It is **just one way** to create a sequence. – Karl Knechtel Nov 12 '22 at 01:01

2 Answers2

3

You can use the following to achieve the same in python:

>>> range(1, 10, 2)
[1, 3, 5, 7, 9]

See documentation on range

You code will therefore be

for i in range(0, 10, 2):
    # do_stuff()
Martin Hallén
  • 1,492
  • 1
  • 12
  • 27
1

When you use a for loop to iterate over an index in Python, usually you construct a range object.

for i in range(10):
    print(i)
# 0, 1, ..., 9

range has a constructor that takes three arguments, start, stop and step.

for i in range(0, 10, 2):
    print(i)
# 0, 2, ..., 8

But usually you just iterate over the items in objects rather than indices.

lst = [0, 1, 2, 3]
for element in lst:
    print(element)
# 0, 1, 2, 3

However, if your object supports slicing (as lists do), it is easy to get every other member.

lst = [0, 1, 2, 3]
for element in lst[::2]: 
    print(element)
# 0, 2

Google "list slicing in Python" if you'd like more information on this syntax.

Jared Goguen
  • 8,772
  • 2
  • 18
  • 36