Size: 5686
Comment: what the heck, tweak some more of the wording
|
← Revision 18 as of 2022-01-23 09:18:40 ⇥
Size: 5594
Comment: Improved structure, added content, linked to iterator wiki page, fixed spelling and grammar mistakes, linked to official python tutorial on for loops, linked to a tutorial with interactive examples
|
Deletions are marked like this. | Additions are marked like this. |
Line 3: | Line 3: |
== Usage in Python == | There are two ways to create loops in Python: with the for-loop and the while-loop. |
Line 5: | Line 5: |
* When do I use for loops? | == When do I use for loops == |
Line 7: | Line 7: |
''for'' loops are traditionally used when you have a piece of code which you want to repeat a fixed number of times. The Python ''for'' statement iterates over the members of a sequence in order. Contrast the ''for'' statement with the [[WhileLoop|WhileLoop]], used when a condition needs to be checked each iteration, or to repeat a piece of code forever. For example: | ''for'' loops are used when you have a block of code which you want to repeat a '''fixed number of times'''. The for-loop is always used in combination with an [[Iterator|iterable object]], like a list or a range. The Python ''for'' statement iterates over the members of a sequence in order, executing the block each time. Contrast the ''for'' statement with the [[WhileLoop|''while'' loop]], used when a condition needs to be checked each iteration or to repeat a block of code forever. For example: |
Line 13: | Line 13: |
print "We're on time %d" % (x) | print("We're on time %d" % (x)) |
Line 22: | Line 22: |
print "To infinity and beyond! We're getting close, on %d now!" % (x) | print("To infinity and beyond! We're getting close, on %d now!" % (x)) |
Line 27: | Line 27: |
As you can see, these loop constructs serve different purposes. The ''for'' loop runs for a fixed amount - in this case, 3, while the ''while'' loop runs until the loop condition changes; in this example, the condition is the boolean ''True'' which will never change, so it could theoretically run forever. You could use a ''for'' loop with a huge number in order to gain the same effect as a ''while'' loop, but what's the point of doing that when you have a construct that already exists? As the old saying goes, "why try to reinvent the wheel?". | When running the above example, you can stop the program by pressing ctrl+c at the same time. As you can see, these loop constructs serve different purposes. The ''for'' loop runs for a fixed amount of times, while the ''while'' loop runs until the loop condition changes. In this example, the condition is the boolean ''True'' which will never change, so it will run forever. |
Line 30: | Line 30: |
* How do they work? | == How do they work? == |
Line 33: | Line 33: |
If you've done any programming before, you have undoubtedly come across a ''for'' loop or an equivalent to it. Many languages have conditions in the syntax of their ''for'' loop - such as a relational expression to determine if the loop is done, and an increment expression to determine the next loop value. In Python this is controlled instead by generating the appropriate sequence. Basically, any object with an iterable method can be used in a ''for'' loop. Even strings, despite not having an iterable method - but we'll not get on to that here. Having an iterable method basically means that the data can be presented in list form, where there are multiple values in an orderly fashion. You can define your own iterables by creating an object with next() and iter() methods. This means that you'll rarely be dealing with raw numbers when it comes to for loops in Python - great for just about anyone! | If you've done any programming before, you have undoubtedly come across a ''for'' loop or an equivalent to it. Many languages have conditions in the syntax of their ''for'' loop, such as a relational expression to determine if the loop is done, and an increment expression to determine the next loop value. In Python, this is controlled instead by generating the appropriate sequence. Basically, any object with an iterable method can be used in a ''for'' loop. Even strings, despite not having an iterable method - but we'll not get on to that here. Having an iterable method basically means that the data can be presented in list form, where there are multiple values in an orderly fashion. You can define your own iterables by creating an object with next() and iter() methods. This means that you'll rarely be dealing with raw numbers when it comes to for loops in Python - great for just about anyone! |
Line 36: | Line 36: |
* Nested loops | == Nested loops == |
Line 39: | Line 39: |
When you have a piece of code you want to run '''x''' number of times, then code within that code which you want to run '''y''' number of times, you use what is known as a "nested loop". In Python, these are heavily used whenever someone has a list of lists - an iterable object within an iterable object. | When you have a block of code you want to run '''x''' number of times, then a block of code within that code which you want to run '''y''' number of times, you use what is known as a "nested loop". In Python, these are heavily used whenever someone has a list of lists - an iterable object within an iterable object. {{{ for x in range(1, 11): for y in range(1, 11): print('%d * %d = %d' % (x, y, x*y)) }}} |
Line 45: | Line 51: |
Like the ''while'' loop, the ''for'' loop can be made to exit before the given object is finished. This is done using the ''break'' statement, which will stop the code from executing any further. You can also have an optional ''else'' clause, which will run should the ''for'' loop exit cleanly - that is, without breaking. == Things to remember == * range vs xrange The ''[[http://docs.python.org/library/functions.html#range|range]]'' function creates a list containing numbers defined by the input. The ''[[http://docs.python.org/library/functions.html#xrange|xrange]]'' function creates a number generator. You will often see that ''xrange'' is used much more frequently than range. This is for one reason only - resource usage. The ''range'' function generates a list of numbers all at once, where as ''xrange'' generates them as needed. This means that less memory is used, and should the ''for'' loop exit early, there's no need to waste time creating the unused numbers. This effect is tiny in smaller lists, but increases rapidly in larger lists as you can see in the examples below. == Examples == ''Nested loops'' |
Like the ''while'' loop, the ''for'' loop can be made to exit before the given object is finished. This is done using the ''break'' statement, which will immediately drop out of the loop and continue execution at the first statement after the block. You can also have an optional ''else'' clause, which will run should the ''for'' loop exit cleanly - that is, without breaking. |
Line 66: | Line 54: |
for x in xrange(1, 11): for y in xrange(1, 11): print '%d * %d = %d' % (x, y, x*y) }}} ''Early exit'' {{{ for x in xrange(3): |
for x in range(3): |
Line 85: | Line 60: |
== Examples == | |
Line 88: | Line 64: |
Line 92: | Line 65: |
for x in xrange(3): print x |
for x in range(3): print(x) |
Line 95: | Line 68: |
print 'Final x = %d' % (x) | print('Final x = %d' % (x)) |
Line 97: | Line 70: |
Line 102: | Line 74: |
Line 108: | Line 77: |
print x | print(x) |
Line 111: | Line 80: |
Line 114: | Line 81: |
Line 121: | Line 85: |
print x | print(x) |
Line 125: | Line 89: |
''Lists of lists'' |
''Loop over Lists of lists'' |
Line 135: | Line 96: |
print x | print(x) |
Line 141: | Line 102: |
Line 164: | Line 122: |
''range vs xrange'' {{{ import time #use time.time() on Linux start = time.clock() for x in range(10000000): pass stop = time.clock() print stop - start start = time.clock() for x in xrange(10000000): pass stop = time.clock() print stop - start }}} ''Time on small ranges'' {{{ import time #use time.time() on Linux start = time.clock() for x in range(1000): pass stop = time.clock() print stop-start start = time.clock() for x in xrange(1000): pass stop = time.clock() print stop-start }}} |
|
Line 223: | Line 123: |
Line 234: | Line 131: |
print x | print(x) |
Line 236: | Line 133: |
== A note on `range` == The [[https://docs.python.org/3/library/functions.html#func-range|''range'']] function is seen so often in ''for'' statements that you might think ''range'' is part of the ''for'' syntax. It is not: it is a Python built-in function that returns a sequence following a specific pattern (most often sequential integers), which thus meets the requirement of providing a sequence for the ''for'' statement to iterate over. Since ''for'' can operate directly on sequences, there is often no need to count. This is a common beginner construct (if they are coming from another language with different loop syntax): {{{ mylist = ['a', 'b', 'c', 'd'] for i in range(len(mylist)): # do something with mylist[i] }}} It can be replaced with this: {{{ mylist = ['a', 'b', 'c', 'd'] for v in mylist: # do something with v }}} Consider {{{for var in range(len(something)):}}} to be a flag for possibly non-optimal Python coding. == More resources == If you'd like to learn more, try these links: * [[https://docs.python.org/3/tutorial/controlflow.html#for-statements|Python.org docs]] * [[https://python.land/introduction-to-python/python-for-loop|Python for loop and while loop]] tutorial with interactive code examples |
For loops
There are two ways to create loops in Python: with the for-loop and the while-loop.
When do I use for loops
for loops are used when you have a block of code which you want to repeat a fixed number of times. The for-loop is always used in combination with an iterable object, like a list or a range. The Python for statement iterates over the members of a sequence in order, executing the block each time. Contrast the for statement with the ''while'' loop, used when a condition needs to be checked each iteration or to repeat a block of code forever. For example:
For loop from 0 to 2, therefore running 3 times.
for x in range(0, 3): print("We're on time %d" % (x))
While loop from 1 to infinity, therefore running forever.
x = 1 while True: print("To infinity and beyond! We're getting close, on %d now!" % (x)) x += 1
When running the above example, you can stop the program by pressing ctrl+c at the same time. As you can see, these loop constructs serve different purposes. The for loop runs for a fixed amount of times, while the while loop runs until the loop condition changes. In this example, the condition is the boolean True which will never change, so it will run forever.
How do they work?
If you've done any programming before, you have undoubtedly come across a for loop or an equivalent to it. Many languages have conditions in the syntax of their for loop, such as a relational expression to determine if the loop is done, and an increment expression to determine the next loop value. In Python, this is controlled instead by generating the appropriate sequence. Basically, any object with an iterable method can be used in a for loop. Even strings, despite not having an iterable method - but we'll not get on to that here. Having an iterable method basically means that the data can be presented in list form, where there are multiple values in an orderly fashion. You can define your own iterables by creating an object with next() and iter() methods. This means that you'll rarely be dealing with raw numbers when it comes to for loops in Python - great for just about anyone!
Nested loops
When you have a block of code you want to run x number of times, then a block of code within that code which you want to run y number of times, you use what is known as a "nested loop". In Python, these are heavily used whenever someone has a list of lists - an iterable object within an iterable object.
for x in range(1, 11): for y in range(1, 11): print('%d * %d = %d' % (x, y, x*y))
- Early exits
Like the while loop, the for loop can be made to exit before the given object is finished. This is done using the break statement, which will immediately drop out of the loop and continue execution at the first statement after the block. You can also have an optional else clause, which will run should the for loop exit cleanly - that is, without breaking.
for x in range(3): if x == 1: break
Examples
For..Else
for x in range(3): print(x) else: print('Final x = %d' % (x))
Strings as an iterable
string = "Hello World" for x in string: print(x)
Lists as an iterable
collection = ['hey', 5, 'd'] for x in collection: print(x)
Loop over Lists of lists
list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] for list in list_of_lists: for x in list: print(x)
Creating your own iterable
class Iterable(object): def __init__(self,values): self.values = values self.location = 0 def __iter__(self): return self def next(self): if self.location == len(self.values): raise StopIteration value = self.values[self.location] self.location += 1 return value
Your own range generator using yield
def my_range(start, end, step): while start <= end: yield start start += step for x in my_range(1, 10, 0.5): print(x)
A note on `range`
The ''range'' function is seen so often in for statements that you might think range is part of the for syntax. It is not: it is a Python built-in function that returns a sequence following a specific pattern (most often sequential integers), which thus meets the requirement of providing a sequence for the for statement to iterate over. Since for can operate directly on sequences, there is often no need to count. This is a common beginner construct (if they are coming from another language with different loop syntax):
mylist = ['a', 'b', 'c', 'd'] for i in range(len(mylist)): # do something with mylist[i]
It can be replaced with this:
mylist = ['a', 'b', 'c', 'd'] for v in mylist: # do something with v
Consider for var in range(len(something)): to be a flag for possibly non-optimal Python coding.
More resources
If you'd like to learn more, try these links:
Python for loop and while loop tutorial with interactive code examples