2

Here I am appending items into a list in an iterative manner:

l = []
for i in range(4):
   l.append(i)
print l  # Ans: [0, 1, 2, 3]

Where as, if I use map() to do the same, I get a different result

l = []
map(l.append, range(4))  # Ans: [None, None, None, None]
Ibrahim Quraish
  • 3,663
  • 2
  • 24
  • 32
  • just fyi there is also `list.extend()` which will append all values in the provided sequence to the list, e.g. `list.extend(range(4))` – mfitzp Sep 21 '18 at 09:40
  • @mfitzp yes, I have already explored list.append(). But curious to know why map() did not work in this case. – Ibrahim Quraish Sep 21 '18 at 09:49
  • not `list.append()` ...`list.extend()` — the first adds a single element to a list, the second adds a list (or any iterable) to the list. As for map, it *did* work, the list was updated (look at it the value of `l` after the map). The output of map contains the return value of `list.append()`, which is *always* `None` – mfitzp Sep 21 '18 at 09:52

1 Answers1

2

Python map returns the values returned for each function call in a list (or a generator).

In this case list.append returns None. Also l is mutable, so it should contain the items.

Adam Shem-Ur
  • 300
  • 2
  • 9