4

Is there a more Pythonic way of defining this function?

def idsToElements(ids):
    elements = []
    for i in ids:
        elements.append(doc.GetElement(i))
    return elements

Maybe its possible with list comprehension. I am basically looking to take a list of ids and change them to a list of elements in something simpler than defining a function.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
konrad
  • 3,544
  • 4
  • 36
  • 75

2 Answers2

29

If a list comprehension is all that you wanted

def idsToElements(ids):
    return [doc.GetElement(i) for i in ids ]
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
15

map() is a Python built-in which does exactly what you want.

def idsToElements(ids):
    return map(doc.GetElement, ids)

The use of map() vs the use of list-comprehensions is discussed here.

The most popular (and accepted answer) conclusion is quoted here:

map may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.

Community
  • 1
  • 1
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131