Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 606
Neo Lok Jun Avatar asked Apr 22 '26 06:04

Neo Lok Jun


1 Answers

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

like image 51
Kobi K Avatar answered Apr 25 '26 01:04

Kobi K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!