{article Dive into Python}{title} {text} {/article}
Iterating with for Loops
Introducing the for Loop
When do I use for loops?
For loops are traditionally used when you have a piece of code which you want to repeat n number of times.
/n is a ASCII Linefeed (LF) Escape Sequence.
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> li = ['a', 'b', 'e']
>>> for s in li:
print (s)
a
b
e
>>> print ("\n".join(li))
a
b
e
The syntax for a for loop is similar to list comprehensions. li is a list, and s will take the value of each element in turn, starting from the first element.
Like an if statement or any other indented block, a for loop can have any number of lines of code in it.
This is the reason you haven't seen the for loop yet: you haven't needed it yet. It's amazing how often you use for loops in other languages when all you really want is a join or a list comprehension
{source}
<!-- You can place html anywhere within the source tags -->
<pre class="brush:py;">
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> li = ['a', 'b', 'e']
>>> for s in li:
print (s)
a
b
e
>>> print ("\n".join(li))
a
b
e
</pre>
<script language="javascript" type="text/javascript">
// You can place JavaScript like this
</script>
<?php
// You can place PHP like this
?>
{/source}
Simple Counters
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> for i in range(5):
print (i)
0
1
2
3
4
>>> li = ['a', 'b', 'c', 'd', 'e']
>>> for i in range(len(li)):
print (li[i])
a
b
c
d
e
>>>
Assigning Consecutive Values, range produces a list of integers, which you then loop through. I know it looks a bit odd, but it is occasionally (and I stress occasionally) useful to have a counter loop.
Don't ever do this. This is Visual Basic−style thinking. Break out of it. Just iterate through the list, as shown in the previous example.
{source}
<!-- You can place html anywhere within the source tags -->
<pre class="brush:py;">
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> for i in range(5):
print (i)
0
1
2
3
4
>>> li = ['a', 'b', 'c', 'd', 'e']
>>> for i in range(len(li)):
print (li[i])
a
b
c
d
e
>>>
</pre>
<script language="javascript" type="text/javascript">
// You can place JavaScript like this
</script>
<?php
// You can place PHP like this
?>
{/source}