3

I am Java programmer. I started learning Python few days ago. I'm wondering: are there any equivalents to

map.forEach(System.out::println)

in Python with lambdas? Or only with for loop:

for e in map: print(e)
0

2 Answers 2

8

There is no equivalent to Java's imperative Iterable.forEach or Stream.forEach method. There's a map function, analogous to Java's Stream.map, but it's for applying transformations to an iterable. Like Java's Stream.map, it doesn't actually apply the function until you perform a terminal operation on the return value.

You could abuse map to do the job of forEach:

list(map(print, iterable))

but it's a bad idea, producing side effects from a function that shouldn't have any and building a giant list you don't need. It'd be like doing

someList.stream().map(x -> {System.out.println(x); return x;}).collect(Collectors.toList())

in Java.

The standard way to do this in Python would be a loop:

for thing in iterable:
    print(thing)
Sign up to request clarification or add additional context in comments.

Comments

0

Python also has a map function and it uses the syntax map(function, iterable, ...)

See Python docs: https://docs.python.org/2/library/functions.html#map

4 Comments

But why this: a = {1, 2, 3} map(lambda x: print(x), a) - won't print anything?
See this SO question: stackoverflow.com/questions/7731213/… I hope it answers your question :)
@Don_Quijote map returns a new list with the same number of elements as the original list. The print function does however not return something. So it is not possible to create this new list.
@Don_Quijote you could however create a new function def custom_print(x): print(x); return x with side effects and then use map(custom_print, a) But I rather don't advise such practices

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.