grindelwaldus
grindelwaldus

Reputation: 35

map() is returning only part of arguments

I have the following code:

a = '0'
b = '256'
mod_add = ['300', '129', '139']
list(map(lambda a, b, x: (a < x) and (x < b), a, b, mod_add))

I'd like to check every element in mod_add, but

list(map(lambda a, b, x: (a < x) and (x < b), a, b, mod_add))

returns only one False. With some values (a = '100', b = '200') it returns 'False', 'False', 'False'.

What am I doing wrong?

Upvotes: 1

Views: 83

Answers (4)

Abdou
Abdou

Reputation: 13274

If you really have to use map:

list(map(lambda x: (a < x) and (x < b), mod_add))

Edit:

In response to the desire to map only one element from the list, it really doesn't make such sense to me to do that. But if that's what you wish to do, you can try:

list(map(lambda x: (a < x) and (x < b), [mod_add[0]]))

I hope this helps.

Upvotes: 2

khelili miliana
khelili miliana

Reputation: 3822

a = '0'
b = '256'
mod_add['300', '129', '139']
map(lambda x: int(a)<int(x)<int(b), mod_add)

Output :

[False, True, True]

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54223

This is really the kind of thing you should prefer list comprehensions for.

min_, max_ = '0', '256'
# do you mean for these to be compared lexicographically?!
# be aware that '0' < '1234567890' < '256' is True

mod_add = ['300', '129', '139']

result = [min_ < mod < max_ for mod in mod_add]
# [False, True, True]

map filter and reduce (now functools.reduce) are mighty tools to be sure, but Python tends to shy away from them in favor of more verbose, easier to read expressions.

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78554

a and b are strings, they will be rightly treated as iterables by map, not constants as you intend. You should either use a list comprehension or not pass a and b as parameters to map:

>>> [a < x < b for x in mod_add]
[False, True, True]

Comparisons can be chained arbitrarily, so (a < x) and (x < b) can be replaced with a < x < b


Comparing integers instead of strings (which is probably what you want) is just another step away:

>>> [int(a) < int(i) < int(b) for i in mod_add]
[False, True, True]

Upvotes: 2

Related Questions