-2

I have a list of int and I'd like to sum a value to all of them. The easy way of doing this is:

[x+y for x in my_list]

Is there a more efficient/pythonic way of doing this?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

2 Answers2

1

No, the list comprehension is, to date, the fastest.

As proved here map performs worse for all except few cases, in which map is only microscopically better.

It however depends on the context. For example if you were running this on a Spark RDD a lambda would allow parallelization.

Also a generator expression, if you don't need a new list, would save memory.

Attersson
  • 4,755
  • 1
  • 15
  • 29
1

I think the way you have it is about as Pythonic as you can get working with lists. Any other option I can think of sacrifices either efficiency or legibility. You could do something like

list(map(y.__add__, my_list))

OR

list(map(partial(operator.add, y), my_list))

If you use an external dependency like numpy:

list(np.array(my_list) + y)

That's definitely not more efficient on its own though. It would only make sense if you wanted np.array(my_list) anyway, and didn't convert back to list.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264