[Tutor] for loop
Martin Walsh
mwalsh at groktech.org
Wed Jun 11 05:22:10 CEST 2008
Sean Novak wrote:
> I know I'm going to feel stupid on this one..
> I would normally write this in PHP like this:
>
> for($i=1; i< count($someArray); $i++)
> {
> print $someArray[i]
> }
>
> essentially,, I want to loop through an array skipping "someArray[0]"
> but in python the for syntax is more like foreach in PHP..
I can think of a few approaches, in no particular order -- the decision
is somewhat data dependent, IMO.
1. Use the enumerate built-in
somelist = ['one', 'two', 'three', 'four']
for count, element in enumerate(somelist):
if count > 0: print element
2a. Slice the list to omit the first element
for element in somelist[1:]:
print element
2b. If somelist is a sequence of strings...
print '\n'.join(somelist[1:])
> I've tried this to no avail
>
> count = 0
> for i in range(1,10):
> if count == 0:
> continue
> else:
> count += 1
> print i
> continue
>
> it prints absolutely nothing.
This never reaches 'print i', because count is not incremented when
count == 0, and so it remains for all of the values in range(1, 10).
HTH,
Marty
More information about the Tutor
mailing list