0

I wonder if when we have many void func that change values of some object inplace (in Python return None) like:

A = []

def foo():
    A.append(range(10))

Will there be any benefits of doing list comprehension with these funcs:

funcs = [ foo1, foo2, foo3, ..., foo10]

[
   func() for func in funcs
]

Is it similar to C++ brackets?

Or is it equivalent in performance to simple for loop:

for func in funcs:
    func()

Which one should I use and why? Mostly Im using Python 3.5 so Im asking about this version :P

EDIT_000:::

I wonder if when we have many func that change values of some object inplace and return some dummy boolean, like:

A = []
dummy = False #edit


def foo():
    A.append(range(10))
    return dummy             #edit, we return dummy not None now

Will there be any benefits of doing list comprehension with these funcs:

funcs = [ foo1, foo2, foo3, ..., foo10]

[
   func() for func in funcs
]

Is it equivalent in performance to simple for loop:

for func in funcs:
    dummy=func()

Or will there be some performance gain when we create list full of dummy (like we get more heat waste by pressing more gas in car so it will run faster)?

Robert GRZELKA
  • 109
  • 2
  • 7
  • Whether a loop or list comprehension is better depends on if you want to just execute the functions or store their `return` values in a list – Chris_Rands Nov 15 '16 at 10:07
  • You would only use a list comprehension when you intend to build a list using the returned values of the functions. – Moses Koledoye Nov 15 '16 at 10:07
  • 2
    No! Please do **not** do that. Using a list comprehension purely for the side effects is considered to be an antipattern. You end up with an ugly list full of `None`. Sure, it gets discarded immediately, but it's still a temporary waste of RAM. – PM 2Ring Nov 15 '16 at 10:09
  • A list comp is't magic. It's _slightly_ faster than using a "traditional" for loop with `.append`, but when you don't really need the list, what's the point? I guess a _possible_ minor benefit is that the loop variable(s) of a list comp in Python 3 are in a new scope, but that's of no real use in the example you've posted. – PM 2Ring Nov 15 '16 at 10:12
  • For your edit, it doesn't matter what you `return`, if you don't want to store the `return` values then don't use a list comprehension – Chris_Rands Nov 15 '16 at 12:05

0 Answers0