简体   繁体   中英

Python for loop - skip to last element

How do we skip to the last element in python?

ITS CLEAR NOW!!!!!!!!!!!!

So for example i have a list

foo = ['hello', 'world','how']

And, I have this loop

for i in foo:
    ----------Codes to skip to last element.--------

therefore, variable 'i' becomes the last element in foo, which is 'how'.

    if i == 'how':
       print 'success!'

And yes, i was wondering if there is any method to do so in a for loop, not outside.

The closest I have found is this:

Python skipping last element in while iterating a list using for loop

Please add in the explanation for your answers on how it works.

Edit: Also, if it's not possible, please explain why(optional).

You don't have to run on the entire list:

foo = ['hello', 'world','how']

for i in foo[:-1]:
    ........

You can also identify if it's the last by doing:

foo = ['hello', 'world','how']

for i in foo:
    if i == foo[-1]:
        print "I'm the last.."

For more information about list you can refer Docs

And you have a very good tutorial here

Another method to skip the last element

>>> for index, item in enumerate(foo):
        if index==(len(foo)-1):
            # last element 
        else:
            # Do something

My understanding is that you want to check whether you've reached the end of the cycle without break ing out of it. Python has beautiful for...else and while..else constructs for that. The else clause is used when the cycle completes without breaking out So that the skeleton for your code:

for word in foo:
   ... you may break out
else:
    print success

Simple and elegant (and more efficient too)

EDIT: OK, now I get what you want. You may use slicing - as it was suggested, but islice of itertools will do the job better:

from itertools import islice:
for word in islice(foo, len(foo)-1):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM