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]
Using Python for loop to iterate over a list. In this syntax, the for loop statement assigns an individual element of the list to the item variable in each iteration. Inside the body of the loop, you can manipulate each list element individually.
Iterating a list means going through each element of the list individually. We iterate over a list whenever we need to use its elements in some operation or perform an operation on the elements themselves.
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.
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']
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)
>>>
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.
My 5 cent:
start_from = 'b'
for val in l[l.index(start_from ) if start_from in l else 0:]:
print val
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With