1

How can I simplify the following:

imgs = []
for i, obj in enumerate(objlist):
    imgs.append(  foo(obj, f"img-{i}.png")  )

where objlist an array of objects and foo is a method that processes the object and saves an image receiving both the object and the new file name, it returns the same name given.

martineau
  • 119,623
  • 25
  • 170
  • 301
Diego Vallejo
  • 55
  • 1
  • 7

1 Answers1

0

This is a simple transformation into a list comprehension:

imgs = [foo(obj, f"img-{i}.png") for (i, obj) in enumerate(objlist)]

(btw you forgot the in in your for loop.

Also, see this answer on the general problem of converting nested for loops into a single list comprehension.

quamrana
  • 37,849
  • 12
  • 53
  • 71