Skip first entry in for loop in python?
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
(not for any iterable
though).
Here is a more general generator function that skips any number of items from the beginning and end of an iterable:
def skip(iterable, at_start=0, at_end=0):
it = iter(iterable)
for x in itertools.islice(it, at_start):
pass
queue = collections.deque(itertools.islice(it, at_end))
for x in it:
queue.append(x)
yield queue.popleft()
Example usage:
>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]
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'
The best way to skip the first item(s) is:
from itertools import islice
for car in islice(cars, 1, None):
pass
# do something
islice
in this case is invoked with a start-point of 1
, and an end point of None
, signifying the end of the iterable
.
To be able to skip items from the end of an iterable
, you need to know its length (always possible for a list, but not necessarily for everything you can iterate on). for example, islice(cars, 1, len(cars)-1)
will skip the first and last items in cars
.