Reputation: 612
I need to get the first and only child element of a node and the child is guaranteed to be there. I could write something like this
def get_first(Node):
for x in Node:
return x
But I was hoping for something more elegant. Does anyone know of something?
Upvotes: 0
Views: 3784
Reputation:
Well, I personally don't see anything wrong with your code. It is clean and will work for any iterable object.
Nevertheless, if you must do away with the for-loop, then you can use next
:
def get_first(Node): # Also, Node should be lowercase according to PEP 8
return next(Node)
However, this will only work for iterators. If Node
is not an iterator, then you can make it one with iter
:
def get_first(Node):
return next(iter(Node))
Upvotes: 1