I recently started learning Python, and the concept of for loops is still a little confusing for me. I understand that it generally follows the format for x in y
, where y
is just some list.
The for-each loop for (int n: someArray)
becomes for n in someArray
,
And the for loop for (i = 0; i < 9; i-=2)
can be represented by for i in range(0, 9, -2)
Suppose instead of a constant increment, I wanted i*=2
, or even i*=i
. Is this possible, or would I have to use a while loop instead?
A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
As you say, a for
loop iterates through the elements of a list. The list can contain anything you like, so you can construct a list beforehand that contains each step.
A for
loop can also iterate over a "generator", which is a small piece of code instead of an actual list. In Python, range()
is actually a generator (in Python 2.x though, range()
returned a list while xrange()
was the generator).
For example:
def doubler(x):
while True:
yield x
x *= 2
for i in doubler(1):
print i
The above for
loop will print
1
2
4
8
and so on, until you press Ctrl+C.
You can use a generator expression to do this efficiently and with little excess code:
for i in (2**x for x in range(10)): #In Python 2.x, use `xrange()`.
...
Generator expressions work just like defining a manual generator (as in Greg Hewgill's answer), with a syntax similar to a list comprehension. They are evaluated lazily - meaning that they don't generate a list at the start of the operation, which can cause much better performance on large iterables.
So this generator works by waiting until it is asked for a value, then asking range(10)
for a value, doubling that value, and passing it back to the for
loop. It does this repeatedly until the range()
generator yields no more values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With