[Tutor] for vs while
alan.gauld at btinternet.com
Sat Sep 29 09:53:20 CEST 2007
"James" <jtp at nc.rr.com> wrote
> I have a dumb question...hopefully someone can shed some light on
> difference between for and while in the situation below.
You got the basic answer but I'll just add a comment.
while is your basic type loop, same as in C and most other languages.
for is really a *foreach* loop. It iterates over
It is not an indexing loop and if you find yourself doing
for n in range(len(collection)):
You should consider whether there is a better way.
for item in collection:
If you really need the index as well as the item then
for n,item in enumerate(collection):
print item, 'at index', n
> I'm trying to iterate through a list I've created. The list
> of a command, followed by a 'logging' message (a message printed to
> console or log file after the command is run).
The easiest way to do this is to put both command and message
in a tuple and have a list of tuples:
> stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ]
stuff = [ ("cat /etc/password" , "viewed /etc/password") ]
for com in stuff:
Get the data structure right and the code will follow.
Just back from vacation in Switzerland :-)
More information about the Tutor