Richard Johnson
Richard Johnson

Reputation: 612

Python ElementTree find first element

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

Answers (2)

user2555451
user2555451

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

BoppreH
BoppreH

Reputation: 10173

Have you tried by index?

def get_first(node):
    return node[0]

Upvotes: 1

Related Questions