Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"For" loop first iteration

I would like to inquire if there is an elegant pythonic way of executing some function on the first loop iteration. The only possibility I can think of is:

first = True for member in something.get():     if first:         root.copy(member)         first = False     else:         somewhereElse.copy(member)     foo(member) 
like image 459
Rince Avatar asked Dec 18 '09 11:12

Rince


People also ask

How do you start a for 1 loop?

Use n+1 in Place of n in the range() Function to Start the for Loop at an Index 1 in Python. This method can be implemented by using the start value as 1 and the stop value as n+1 instead of default values 0 and n , respectively.

Does for loop start 0 or 1?

Most loops starts with 0.

What are the two types of iteration?

There are two ways in which programs can iterate or 'loop': count-controlled loops. condition-controlled loops.


1 Answers

Something like this should work.

for i, member in enumerate(something.get()):     if i == 0:          # Do thing     # Code for everything 

However, I would strongly recommend thinking about your code to see if you really have to do it this way, because it's sort of "dirty". Better would be to fetch the element that needs special handling up front, then do regular handling for all the others in the loop.

The only reason I could see for not doing it this way is for a big list you'd be getting from a generator expression (which you wouldn't want to fetch up front because it wouldn't fit in memory), or similar situations.

like image 182
Daniel Bruce Avatar answered Sep 27 '22 19:09

Daniel Bruce