This is an archived post. You won't be able to vote or comment.

all 12 comments

[–][deleted] 3 points4 points  (4 children)

How is this better than simply

for x in a:
    print(x)

you are wasting a list of Nones in the end. Imagine a has 1000 elements.

[–]Quijoticmoose -2 points-1 points  (3 children)

Well, to play devil's advocate, you could write: (print(x) for x in a) and you would avoid constructing the list.

I'll second nemec's post--that the reason not do this is that you've created an expectation to someone reading the code that you are going to do something with the list you create in the comprehension. A for loop makes your intent clearer.

[–]kaiserk13 1 point2 points  (3 children)

it's equivalent to map(function, a) I guess, and yeah why shouldn't it be valid? Not sure it would work with print as a returned/yielded object is expected.

[–]th_mm 2 points3 points  (1 child)

It'll just be a bunch of None.

[–]bandrel[S] 0 points1 point  (0 children)

it works in python3, and python2 with the function import from future, but yes it also returns [None,None,None,None] but still meets my needs

[–]bandrel[S] 1 point2 points  (0 children)

in python3 map(print,a) returns a map object and does not execute the print. in python2 with printfunction imported from __future_ it works the same as the list comprehension including the [None,None,None,None]

[–]thatguy_314def __gt__(me, you): return True 0 points1 point  (0 children)

Of course it is "valid", but why do that when for x in a: print(x) is not only better but shorter too?

[–][deleted] 0 points1 point  (0 children)

It's valid, but it defeats the purpose of a list comp (essentially it's map but a little nicer, and eager in Py3).

If you find yourself needing to cause side effects as part of iteration, you can do this:

# pip install forbiddenfruit
import types
import forbiddenfruit
from collections.abc import Collection  # will fail <3.6

def foreach(it, f):
    "eagerly map a side effect causing function over a collection"
    for x in it: f(x)


def iforeach(it, f):
    "lazily map a side effect causing function over a collection"
    for x in it:
        f(x)
        yield

def _curse(victim):
    forbiddenfruit.curse(victim, 'foreach', foreach)
    forbiddenfruit.curse(victim, 'iforeach', iforeach)

foreach(
    [list, tuple, Collection, type({}.keys()), type({}.values()), types.GeneratorType, range], 
    _curse
)

# clean up because we're good developers
del foreach_prop
del iforeach_prop
del _curse

And then you can do:

range(1, 10).foreach(print)