tags:

views:

202

answers:

6

Suppose I have this list:

thelist = ['apple','orange','banana','grapes']
for fruit in thelist:

This would go through all the fruits.

However, what if I wanted to start at orange? Instead of starting at apple? Sure, I could do "if ...continue", but there must be a better way?

+1  A: 
for fruit in thelist[1:]:
    print fruit
Tzury Bar Yochay
fixed, yet it was just for the concept
Tzury Bar Yochay
+10  A: 

using python's elegant slices

>>> for fruit in thelist[1:]:
>>>    print fruit
tosh
+2  A: 
for fruit in thelist [1:]:

will start at the second element in the list.

Tim Pietzcker
+14  A: 
for fruit in thelist[1:]:
    ...

this of course suppose you know at which index to start. but you can find the index easily:

for fruit in thelist[thelist.index('orange'):]:
    ...
Adrien Plisson
+1 for illustrating a semantic approach. nice!
tosh
btw. you might want to call .index on "thelist" instead of "fruit" :)
tosh
ooops... my mistake. corrected !
Adrien Plisson
A: 

Slices make copies of lists, so if there are many items, or if you don't want to separately search the list for the starting index, an iterator will let you search, and then continue from there:

>>> thelist = ['apple','orange','banana','grapes']
>>> fruit_iter = iter(thelist)
>>> target_value = 'orange'
>>> while fruit_iter.next() != target_value: pass
...
>>> # at this point, fruit_iter points to the entry after target_value
>>> print ','.join(fruit_iter)
banana,grapes
>>>
Paul McGuire
+3  A: 

As mentioned by Paul McGuire, slicing a list creates a copy in memory of the result. If you have a list with 500,000 elements then doing l[2:] is going to create a new 499,998 element list.

To avoid this, use itertools.islice:

>>> thelist = ['a', 'b', 'c']

>>> import itertools

>>> for i in itertools.islice(thelist, 1, None):
...     print i
...
b
c
Steve Losh