Skip first entry in for loop in python?


Question

In python, How do I do something like:

for car in cars:
   # Skip first and last, do work for rest
1
151
5/12/2014 2:21:34 PM

Accepted Answer

The other answers only work for a sequence.

For any iterable, to skip the first item:

itercars = iter(cars)
next(itercars)
for car in itercars:
    # do work

If you want to skip the last, you could do:

itercars = iter(cars)
# add 'next(itercars)' here if you also want to skip the first
prev = next(itercars)
for car in itercars:
    # do work on 'prev' not 'car'
    # at end of loop:
    prev = car
# now you can do whatever you want to do to the last one on 'prev'
219
4/9/2012 8:17:58 PM

To skip the first element in Python you can simply write

for car in cars[1:]:
    # Do What Ever you want

or to skip the last elem

for car in cars[:-1]:
    # Do What Ever you want

You can use this concept for any sequence.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon