[Tutor] Usage of for loop
A.T.Hofkamp
a.t.hofkamp at tue.nl
Mon Jan 5 15:14:56 CET 2009
vanam wrote:
> Hi all,
> i am beginner to this python language and slowing learning the language by
> referring docs.I am trying to understand the for loop i.e., usage of for
> loop in python,unlike c where i can give condition in python it is simple
In C, the for-loop is just a hidden 'while'. You can think of
(I dropped the variable declaration stuff, and the cumbersome ";" and printf()
syntax for clarity)
a = ["cat", "window","defenestrate"]
for (i=0; i < len(a) ; i = i + 1) {
x = a[i]
print x
}
as the equivalent of
a = ["cat", "window","defenestrate"]
i = 0
while i < len(a):
x = a[i]
print x
i = i + 1
Now take a step back.
What are you aiming to achieve here?
If you look carefully, the whole i variable is not relevant. The aim of the
code is to get each element of the list a in x (one element with each
iteration), and do something with it, in this case, printing it.
To demonstrate, let's sum all values of list b:
b = [1, 2, 3]
total = 0
i = 0
while i < len(b):
y = b[i]
total = total + y
i = i + 1
If you compare both pieces, you see the same pieces of boilerplate code appear:
i = 0
while i < len(<LIST>):
<VAR> = <LIST>[i]
and
i = i + 1
This happens at every loop that you write.
The Python developers decided that Python should take care of the boilerplate
code. Of the first 3 lines, the interesting pieces are only <LIST> (the list
you get values from), and <VAR> (the name of variable where you put each
element in with each iteration).
The line at the bottom is always the same, no need to enter that each time.
What you are left with after throwing out the boilerplate code (in pseudo
english/Python), for your original problem, is something like
"for each element" x "from the list" a "do"
print x
which is shortened in Python to
for x in a:
print x
('in' is ASCII for the 'element of' symbol U+2208).
Not only is this much shorter, it is also more powerful. Python has many rich
data structures (such as lists, tuples, sets, dictionaries), and the above
construct can be used for all of them.
Sincerely,
Albert
More information about the Tutor
mailing list