Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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]

like image 470
John Avatar asked Jun 09 '11 15:06

John


People also ask

Can you iterate over a list with a for loop?

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.

What does iterating through a list mean?

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.

How do you make a loop that goes through a list?

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.


2 Answers

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.

like image 138
brandizzi Avatar answered Nov 15 '22 23:11

brandizzi


My 5 cent:

start_from = 'b'

for val in l[l.index(start_from ) if start_from  in l else 0:]:
   print val
like image 26
Artsiom Rudzenka Avatar answered Nov 16 '22 01:11

Artsiom Rudzenka