3

I have a list of strings that print out just fine using a normal loop:

for x in listing:
    print(x)

I thought it should be pretty simple to use a lambda to reduce the loop syntax, and kickstart my learning of lambdas in Python (I'm pretty new to Python).

Given that the syntax for map is map(function, iterable, ...) I tried:

map(lambda x: print(x), listing)

But this does not print anything out (it also does not produce an error). I've done some searching through material online but everything I have found to date is based on Python 2, namely mentioning that with Python 2 this isn't possible but that it should be in Python 3, without explicitly mentioning how so.

What am I doing wrong?

0

2 Answers 2

3

In python 3, map returns an iterator:

>>> map(print, listing)
<map object at 0x7fabf5d73588>

This iterator is lazy, which means that it won't do anything until you iterate over it. Once you do iterate over it, you get the values of your list printed:

>>> listing = [1, 2, 3]
>>> for _ in map(print, listing):
...     pass
... 
1
2
3

What this also means is that map isn't the right tool for the job. map creates an iterator, so it should only be used if you're planning to iterate over that iterator. It shouldn't be used for side effects, like printing values. See also When should I use map instead of a for loop.

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

Comments

3

I wouldn't recommend using map here, as you don't really care about the iterator. If you want to simplify the basic "for loop", you could instead use str.join():

>>> mylist = ['hello', 'there', 'everyone']
>>> '\n'.join(mylist)
hello
there
everyone

Or if you have a non-string list:

>>> mylist = [1,2,3,4]
>>> '\n'.join(map(str, mylist))
1
2
3
4

1 Comment

Thanks. While Aran-Fey's answer does answer the question I asked, your answer shows me how to do what I actually wanted, so both equally valid IMO :)

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.