3

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

Community
  • 1
  • 1
Lok Jun
  • 1,315
  • 2
  • 9
  • 16

3 Answers3

6

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

Kobi K
  • 7,743
  • 6
  • 42
  • 86
2

Another method to skip the last element

>>> for index, item in enumerate(foo):
        if index==(len(foo)-1):
            # last element 
        else:
            # Do something
Vb407
  • 1,577
  • 2
  • 15
  • 27
  • Why enumerate? Can you explain? – Lok Jun Dec 25 '13 at 10:23
  • enumerate will make certain loops a bit clearer. you will get index of the item along with the item in the sequence.As you need to skip the last element I have taken index and compared it with the len of list to skip the last – Vb407 Dec 25 '13 at 10:26
1

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):
volcano
  • 3,578
  • 21
  • 28
  • What breakout? What do you mean? – Lok Jun Dec 25 '13 at 10:33
  • In a loop, you may put code _if something: break_ . The meaning is that if condition _something_ evaluates to true, your loop will be interrupted immediately. – volcano Dec 25 '13 at 10:39
  • That's for everyone to refer to only. I am making sure they can add all they want. Also, you can help edit, because it is unclear from the comments – Lok Jun Dec 25 '13 at 10:41