Gianni Spear
Gianni Spear

Reputation: 7946

append in a list in Python using result value or a function

are the both approaches equivalent from a point of view of performance and coding-style?

def foo(n):
    return n*2

# case 1 with ".append(function())"

mylist = [1,2,3,4,5,6,7,8,9,10]
result = list()
for l in mylist:
    result.append(foo(l))

# case 2 ".append(result)"

mylist = [1,2,3,4,5,6,7,8,9,10]
result = list()
for l in mylist:
    r = foo(l)
    result.append(r)

Upvotes: 0

Views: 1335

Answers (4)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

Your approaches are more or less equivalent; option 2 does a little more work; it has to do an extra store and name lookup for the temporary variable. In practice, the difference is minimal and you should be focusing on code readability more than premature optimization.

For your specific example you'd be much better off using a list comprehension:

result = [foo(l) for l in mylist]

The list comprehension constructs the list in C code and does not have to look up the .append() method each loop iteration.

Upvotes: 3

Abhijit
Abhijit

Reputation: 63757

You might have some performance gain in just removing the tempoarary assignment, but remember, premature optimization is evil, and micro-optimization is not worth the effort

Off course there are better ways to do, for example

List Comprehension

mylist = [1,2,3,4,5,6,7,8,9,10]
result = [n*2 for n in mylist]

Upvotes: 2

user2665694
user2665694

Reputation:

result = [foo(i) for i in mylist]

is what you want.

Upvotes: 1

kkonrad
kkonrad

Reputation: 1262

I think they are the same, but best option would be map(foo, mylist) - even from performance point of view as append can cause list resize which takes extra time

Upvotes: 2

Related Questions