0

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!

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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?

Comments

1

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'])
    

Comments

0

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.)

1 Comment

I thought it was implied that I'm asking if list comprehension can be used for more than creating lists, but thank you for your answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.