user2622016
user2622016

Reputation: 6413

How to skip first element in `for` loop?

Is there a robust, universal way in python to skip first element in the for loop?

The only way I can think of is to write a special generator by hand:

def skipFirst( it ):
    it = iter(it) #identity for iterators
    it.next()
    for x in it:
        yield x

And use it for example like:

for x in skipFirst(anIterable):
    print repr(x)

and like:

doStuff( str(x) for x in skipFirst(anIterable) )

and like:

[ x for x in skipFirst(anIterable) if x is not None ]

I know we can do slices on lists (x for x in aList[1:]) but this makes a copy and does not work for all sequences, iterators, collections etc.

Upvotes: 15

Views: 33442

Answers (4)

Neeraj Sharma
Neeraj Sharma

Reputation: 1362

for i in list1[1:]: #Skip first element
    # Do What Ever you want

Explanation:

When you use [1:] in for loop list it skips the first element and start loop from second element to last element

Upvotes: 23

Derek Litz
Derek Litz

Reputation: 10897

def skip_first(iterable):
    """Short and sweet"""

    return (element for i, element in enumerate(iterable) if i)

def skip_first_faster(iterable):
    """Faster, but meh"""

    generator = (element for element in iterable)
    next(generator, None) # None Prevents StopIteration from being raised

    return generator

if __name__ == '__main__':
    for item in skip_first(range(5)):
        print item

    for item in skip_first_faster(range(5)):
        print item

Upvotes: -1

Martijn Pieters
Martijn Pieters

Reputation: 1121446

When skipping just one item, I'd use the next() function:

it = iter(iterable_or_sequence)
next(it, None)  # skip first item.
for elem in it:
    # all but the first element

By giving it a second argument, a default value, it'll also swallow the StopIteration exception. It doesn't require an import, can simplify a cluttered for loop setup, and can be used in a for loop to conditionally skip items.

If you were expecting to iterate over all elements of it skipping the first item, then itertools.islice() is appropriate:

from itertools import islice

for elem in islice(it, 1, None):
    # all but the first element

Upvotes: 16

user2622016
user2622016

Reputation: 6413

I think itertools.islice will do the trick:

islice( anIterable, 1, None )

Upvotes: 6

Related Questions