Why For Loop Skips the Last element?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jan 1 11:15:20 CET 2015


Thuruv V wrote:

> Hi all,
> 
> Here's the list. .

The exact details of the list are not important. Please simplify your code
to something easier to handle than this:

> 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)' ]

For your testing, try this first:

inlist = ['Female 1', 'male 1', 'Male 2', 'ladies 2']


When you have your code working with the simple test data, then you can go
on with the more complicated real data.


> My code :

Why are you using a while loop? I don't understand where this comes from. So
many beginners keep doing things the hard way, using a while loop.


Iterate over the list like this:


for item in inlist:
    item = item.lower()
    if "female" in item or "ladies" in item:
        print("Female")
    elif "man" in item or "male" in item:
        print("Male")




> 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.

Your code skips that last item because the second-last item doesn't have the
word "watch" in it, so the loop never advances and it just loops forever.

But really, the code you show us is not the code you are actually using. Why
do you show us something different from what you actually use?

I know that the code you show cannot possibly be the code you are using,
because the code you show fails. If you ran this code, it would raise
TypeError.




-- 
Steven




More information about the Python-list mailing list