Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map,lambda and append.. why doesn't it work?

So I'm trying to do this.

a = []
map(lambda x: a.append(x),(i for i in range(1,5))) 

I know map takes a function but so why doesn't it append to the list? Or is append not a function? However printing a results to a still being empty

now an interesting thing is this works

a = []

[a.append(i) for i in range(5)]
print(a)

aren't they basically "saying" the same thing?

It's almost as if that list comprehension became some sort of hybrid list-comprehension function thing

So why doesn't the lambda and map approach work?

like image 267
Zion Avatar asked Dec 06 '22 20:12

Zion


2 Answers

I am assuming you are using Python 3.x , the actual reason why your code with map() does not work is because in Python 3.x , map() returns a generator object , unless you iterate over the generator object returned by map() , the lambda function is not called . Try doing list(map(...)) , and you should see a getting filled.

That being said , what you are doing does not make much sense , you can just use -

a = list(range(5))
like image 60
Anand S Kumar Avatar answered Dec 22 '22 16:12

Anand S Kumar


append() returns None so it doesn't make sense using that in conjunction with map function. A simple for loop would suffice:

a = []
for i in range(5):
    a.append(i)
print a

Alternatively if you want to use list comprehensions / map function;

a = range(5) # Python 2.x
a = list(range(5)) # Python 3.x
a = [i for i in range(5)]
a = map(lambda i: i, range(5)) # Python 2.x
a = list(map(lambda i: i, range(5))) # Python 3.x

[a.append(i) for i in range(5)]

The above code does the appending too, however it also creates a list of None values as the size of range(5) which is totally a waste of memory.

>>> a = []
>>> b = [a.append(i) for i in range(5)]
>>> print a
[0, 1, 2, 3, 4]
>>> print b
[None, None, None, None, None]
like image 22
Ozgur Vatansever Avatar answered Dec 22 '22 15:12

Ozgur Vatansever