aralar
aralar

Reputation: 3120

When does using list comprehension in Python become inefficient?

I see that using list comprehension provides a very simple way to create new lists in Python.

However, if instead of creating a new list I just want to call a void function for each argument in a list without expecting any sort of return value, should I use list comprehension or just use a for loop to iterate? Does the simplicity in the code justify creating a new list (even if it remains empty) for each set of iterations? Even if this added cost is negligible in small programs, does it make sense to do it in large-scale programs/production?

Thanks!

Upvotes: 0

Views: 173

Answers (4)

espang
espang

Reputation: 683

There are more possible solutions for calling a funcion on every member of a list:

  • numpy can vectorize functions

    import numpy as np
    
    def func(i):
        print i
    
    v_func = np.vectorize(func)
    v_func(['one', 'two', 'three'])
    
  • python has a builtin map function, that maps a function on every member of an iterable

    def func(i):
        print i
    map(func, ['one', 'two', 'three'])
    

Upvotes: 1

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

List comprehensions are the wrong way if you don't actually need a list. Use this instead:

for i in seq:
    some_function(i)

This is both more efficient and more expressive than using:

[some_function(i) for i in seq]

Note that there is something similar that doesn't work (and in particular it's not a tuple comprehension):

(some_function(i) for i in seq)

because that only creates an iterator. If you actually pass a list around that only gets iterated once, passing such an iterator around is a much better solution though.

Upvotes: 3

Scott Hunter
Scott Hunter

Reputation: 49813

Are you asking if it is inefficient to create a list you don't need? Put that way, the answer should be obvious.

(To satisfy the answer police: yes, it is less efficient to create a list you don't need.)

Upvotes: 0

Moritz
Moritz

Reputation: 4761

for x in lst: f(x)

looks about equally short (it's actually one character shorter) as

[f(x) for x in lst]

Or is that not what you were trying to do?

Upvotes: 2

Related Questions