0

Why this map do not work at command line?

Just fails silently:

python -c "x=range(1000);map(lambda l: print(l), x)"

The map should traverse the range as it works inside Python REPL.

2
  • try calling python3 -c ... - python is normally Python 2 Commented Feb 18, 2016 at 19:40
  • 2
    Side-note: Using map for its side-effects is considered bad form; it's doubly bad because you rely on lambda functions unnecessarily (map(print, x) would be identical and not involve pointless slowdown/verbosity from lambda wrapping). A better solution is either: print(*x, sep="\n") which prints all at once (fine for smallish output sequences, but not for millions of outputs) or just using an explicit loop for l in x: print(l) (though the latter may not work well for one-liners). If you must map, just list-ify to force map to run: list(map(print, x)). Commented Feb 18, 2016 at 20:01

2 Answers 2

1

You are probably trying to run with python2.x (to make sure try running python --version)

In python 2 lambda l: print(l) is not valid, since print is not a regular function/method.

Try running

python3 -c "x=range(1000);map (lambda l:print(l), x)΅

If you want a solution that is compatible with both versions, try:

python -c "x=range(1000); print('\n'.join(map(lambda l: str(l), x)))"

Bonus: A solution using list comprehensions:

python -c "x=range(1000); print('\n'.join([ str(l) for l in x ]))"
Sign up to request clarification or add additional context in comments.

1 Comment

map(print, x) and map(str, x) are a little more terse, no need for lambdas.
1

When you run this code (in python 3), the code is functioning correctly. However, that the code returns is a map object, which contains the instructions to print the numbers, as is shown here

>>> x=range(1000);map (lambda l:print(l), x)
<map object at 0x6ffffd0cba8>

To get the numbers to print, you would need to iterate over the map, like

>>> x=range(1000)
>>> y=map (lambda l:print(l), x)
>>> for n in y:
...   pass
...
0
1
2
3
4
5
6
7
8
etc.

Comments

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.