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.