Why For Loop Skips the Last element?

Jussi Piitulainen jpiitula at ling.helsinki.fi
Thu Jan 1 04:31:08 EST 2015


Thuruv V writes:

> Here's the list. .
> 
> inlist = ["Fossil Women's Natalie Stainless Steel Watch Brown (JR1385)",
> 'Balmer Swiss Made Veyron Mens Watch: Black Band/ Black Dial (62625241)',
> 'Fortune NYC Ladies Quilted Dial Watch: Brown',
> 'Jeanne Collection w/ Swarovski Elements Watch: Dark Purple Band
> (62623659)',
> 'Swiss Legend Commander Chronograph: Watch Orange/Black (SL-10067-01-ORS)',
> 'Debussy Ladies Watch: Brown/Gray/Silver 14070 - 62625292',
> '#2 Swiss Legend Commander Chronograph: Green (SL-10067-BB-017)',
> 'Auguste Jaccard 3 Timezone Watch: Black Band/ Gray & Black Dial (62625184)'
> ]
> 
> My code :
> i = 0
> while i <= len(inlist):
>     if 'watch' in str(inlist[i]).lower() or 'watches' in
> str(inlist[i]).lower():
>         if 'women' in str(inlist[i]).lower() or 'female' in
> str(inlist[i]).lower() or 'ladies' in str(inlist[i]).lower():
>             print 'FEMale Watch', inlist.index(i),str(i)
>         elif 'men' in str(inlist[i]).lower() or 'male' in
> str(inlist[i]).lower() or 'chronograph' in str(inlist[i]).lower():
>             print 'Male Watch',inlist.index(i),str(i)
>         i = next(inlist)
> 
> When on executing python skips the last element('Auguste Jaccard 3
> Timezone Watch: Black Band/ Gray & Black Dial (62625184)') in the
> list.

Looks like it should raise an exception at the first element, as soon
as it tries to print inlist.index(0). And looks like you are confusing
the element and the index of the element all the way through.

Also, re subject line, that's not a for loop. That's a while loop. But
since you mean it to go through all elements of the list, a for loop
is indeed preferable:

    for line in inlist:
       print(line)

To walk each line and its index together, use enumerate:

   for i, line in enumerate(inlist):
       print(i, line)

(The "i = next(inlist)" in your while loop wants to be "i += 1", and
it really doesn't want to be inside the if-statement. But since your
while loop wants to be a for loop, the whole update of the index
should go away.)

> But when accessing through 'print inlist[0]' is possible,i.e it
> shows the e;lement. but the list skips it. .
> Please enlighten me. .
> Thanks.

I suspect you didn't post quite the version of the code you ran, but
maybe the above suggestions help you get on track again. Best wishes.



More information about the Python-list mailing list