15

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.

0

4 Answers 4

23
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

6
  • Hiya there, while this may well answer the question, please be aware that other users might not be as knowledgeable as you. Why don't you add a little explanation as to why this code works? Thanks!
    – Vogel612
    Commented Apr 10, 2015 at 8:38
  • Thanks for your suggestion. Explanation : for i in list1[1:]: When you use [1:] in for loop list it skips the first element and start loop from second element to last element. Commented Sep 23, 2015 at 6:22
  • 2
    This solution is not correct, it does not skip element, but makes a copy without first element. Probably not what user wants to do. Commented Mar 13, 2018 at 13:38
  • You don’t want to do this if the list is large. You can’t do this if the object in question isn’t a sequence (not a list or tuple or string or similar), but is instead just an iterable. Commented Jul 17, 2019 at 1:20
  • +1 This was the correct answer for me, just overwrite the original list: list1 = list1[1:] for i in list: # do stuff here
    – Cameron B
    Commented Mar 23, 2020 at 8:09
16

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
3
  • Using the builtin next also has the advantage of working in both Python2 and Python3. Python3 renames the it.next() special method to it.__next__(). Commented Dec 19, 2013 at 13:19
  • 1
    @SteveJessop: yup, and you don't have to catch the StopIteration exception. Commented Dec 19, 2013 at 13:20
  • @MartijnPieters: right, that's the thing that my thing was "also" to :-) The questioner's code doesn't catch StopIteration, but should... Commented Dec 19, 2013 at 13:20
6

I think itertools.islice will do the trick:

islice( anIterable, 1, None )
0
-1
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
1
  • Don’t use a generator expression here. iter() is much more efficient and produces an iterator that doesn’t have to resort to a Python for construct just to loop. Commented Jul 17, 2019 at 1:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.