Complete beginner, any help appreciated :) - For Loops

Dave Angel d at davea.name
Thu Dec 1 06:56:44 EST 2011


On 12/01/2011 06:32 AM, Pedro Henrique G. Souto wrote:
>
> On 01/12/2011 08:53, Mark wrote:
>> Hi there,
>>
>> I'm a complete beginner to Python and, aside from HTML and CSS, to 
>> coding in general. I've spent a few hours on it and think I 
>> understand most of the syntax.
>>
>> However, I'm wondering a bit about For Loops. I know that the basic 
>> syntax for them is to define a list, and then to use something like:
>>
>> for x in y
>>
>> However, what does "for" and "in" mean in this context? Can anyone 
>> help me to understand this? I know it's a really basic question, but 
>> hopefully it will see me on my way to coding properly :)
>>
>> Thanks a lot.
>
> That means (in a free translation)
>
> "For each one of 'x' in 'y', do this"
>
> 'y' is a list, for example, then it means: "For each one of the 
> elements of the list 'y' (the element on the current iteration is 
> named 'x'), do this"
>
>
And if y is a string, it means

for each character in y, do this
      x = the character
      (then do the indented part)

And if y is an arbitrary iterable, it means

     for each thing the iterable produces
           x = the thing
          (then do the indented part)

Each time you go through the loop, x will be equal to the next item in 
the sequence.  So you can systematically process the items in the list 
(or characters in the string, or values from an iterable), one at a time.

The only real caveat is to not do something that would change the list 
(etc.) while you're looping through it.

What are some other examples of iterables?

infile = open("myfile.txt", "r")      #infile is an iterable
for line in infile:
      print "**", line, "**"

for val in  (1, 4, 9, 2007)

for x in xrange(50000000):
      #this does the same as range(), but doesn't actually build the list.
      #this way, we don't run out of memory

You can also code your own generator function, which is an iterable, and 
may be used like the above.

Some things in this message assume Python 2.x.  in Python 3, range works 
differently, as does print.


-- 

DaveA




More information about the Python-list mailing list