0

Here is my code.

rst2 = []
def a(n):
    return rst2.append(1)

a = map(a, [2, 2])

print(rst2)

Can somebody tell me why the rst2[] return a blank?

I tried to change the rst2 to global rst2, but it does not work.

jy05un
  • 1
  • 1
    See the dupe for the direct answer. But more broadly, using `map` this way is *very* unidiomatic. `map` is intended as a purely-functional streaming function, and using it with a function that has (very explicit) side effects is extremely counterintuitive. If the goal is to mutate some other data, you'll find a `for` loop more readable. – Silvio Mayolo Feb 23 '23 at 01:39
  • 1
    `map()` returns a generator that does "nothing" until use via something like `next(a)` or `list(a)`. Doing either of those will begin to popolate `rst2`. The use of `map()` like this for side effects is strongly discouraged by me. see also: https://stackoverflow.com/questions/75539726/i-wonder-if-the-value-changes-depending-on-whether-or-not-a-list-is-applied-to-t/75539800#75539800 – JonSG Feb 23 '23 at 01:48

0 Answers0