Greetings pyc-sires and py-ladies, 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)
You have several choices for the Head-Tail design pattern.
Or this
People whine that this is somehow not "DRY" because the "redundant foo(member)" code. That's a ridiculous claim. If that was true then all functions could only be used once. What's the point of defining a function if you can only have one reference?
Here, I could come with a Pythonic idiom that can look "pertty". Although, most likely I'd use the form you suggested in asking the question, just for the code to remain more obvious, though less elegant.
(sorry - the first I posted, before editing, form would not work, I had forgotten to actually get an iterator for the 'copy' object)
This works:
In most cases, though, I'd suggest just iterating over
whatever[1:]
and doing the root thing outside the loop; that's usually more readable. Depends on your use case, of course.Something like this should work.
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.
How about using
iter
, and consuming the first element?Edit: Going back on the OP's question, there is a common operation that you want to perform on all elements, and then one operation you want to perform on the first element, and another on the rest.
If it's just a single function call, I'd say just write it twice. It won't end the world. If it's more involved, you can use a decorator to wrap your "first" function and "rest" function with a common operation.
Output:
or you could do a slice:
how about:
or maybe:
Documentation of index-method.