do-me
do-me

Reputation: 2188

How can I retrieve the remaining items in a for loop in Python?

I have a simple for loop iterating over a list of items. At some point, I know it will break. How can I then return the remaining items?

for i in [a,b,c,d,e,f,g]:
    try: 
        some_func(i)
    except:
        return(remaining_items) # if some_func fails i.e. for c I want to return [c,d,e,f,g]

I know I could just take my inital list and delete the the items from the beginning for every iteration one by one. But is there maybe some native Python function for this or something more elegant?

Upvotes: 3

Views: 1265

Answers (3)

Ratnakar BACHU
Ratnakar BACHU

Reputation: 11

def test():
    myList = [1,2,3,4,0,7,8,9]
    for index, item in enumerate(myList):
        try: 
            print(index,item)
            1/item
        except:
            return(myList[index:]) 

Upvotes: 0

Pac0
Pac0

Reputation: 23174

You can make use of enumerate that yields both the element and its index in the list.

myList = [a,b,c,d,e,f,g]
for index, item in enumerate(myList):
    try: 
        some_func(item)
    except:
        return myList[index:]

Test-it online

Upvotes: 6

azro
azro

Reputation: 54168

You could use itertools.dropwhile, you use a test method to apply some_func, when it raises an error, the test becomes False and so it stops and dropwhile return the remaining ones

from itertools import dropwhile
    
def my_fct():
    def test(v):
        try:
            some_func(v)
            return False
        except:
            return True    
    return list(dropwhile(test, [a, b, c, d, e, f, g]))

Upvotes: 1

Related Questions