Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...