in Python how do i loop through list starting at a key and not the beginning.
e.g.
l = ['a','b','c','d']
loop through l but starting at b e.g. l[1]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The straightforward answer
Just use slicing:
It will generate a new list with the items before
1removed: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:Also note that, since it returns an interator, you can iterate over it only once:
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 onitertools.islice()when my list has thousands of items, or when I iterate over hundreds of different slices.