Looping through a list from a specific key to the end of the list

My 5 cent:

start_from = 'b'

for val in l[l.index(start_from ) if start_from  in l else 0:]:
   print val

The straightforward answer

Just use slicing:

>>> l = ['a','b','c','d']
>>> for i in l[1:]:
...     print(i)
... 
b
c
d

It will generate a new list with the items before 1 removed:

>>> l[1:]
['b', 'c', 'd']

A more efficient alternative

Alternatively, if your list is huge, or you are going to slice the list a lot of times, you can use itertools.islice(). It returns an iterator, avoiding copying the entire rest of the list, saving memory:

>>> import itertools
>>> s = itertools.islice(l, 1, None)
>>> for i in s:
...     print(i)
... 
b
c
d

Also note that, since it returns an interator, you can iterate over it only once:

>>> import itertools
>>> s = itertools.islice(l, 1, None)
>>> for i in s:
...     print(i)
... 
b
c
d
>>> for i in s:
...     print(i)
>>>

How to choose

I find slicing clearer/more pleasant to read but itertools.islice() can be more efficient. I would use slicing most of the time, relying on itertools.islice() when my list has thousands of items, or when I iterate over hundreds of different slices.


This will loop through items in l beginning with 1:

for i in l[1:]:
    #do something with i

Tags:

Python