primes = [2,3,5,7..] (prime numbers)
map(lambda x:print(x),primes)
It does not print anything.
Why is that?
I've tried
sys.stdout.write(x)
too, but doesn't work either.
Since lambda x: print(x) is a syntax error in Python < 3, I'm assuming Python 3. That means map returns a generator, meaning to get map to actually call the function on every element of a list, you need to iterate through the resultant generator.
Fortunately, this can be done easily:
list(map(lambda x:print(x),primes))
Oh, and you can get rid of the lambda too, if you like:
list(map(print,primes))
But, at that point you are better off with letting print handle it:
print(*primes, sep='\n')
NOTE: I said earlier that '\n'.join would be a good idea. That is only true for a list of str's.
This works for me:
>>> from __future__ import print_function
>>> map(lambda x: print(x), primes)
2
3
5
7
17: [None, None, None, None]
Are you using Python 2.x where print is a statement, not a function?
Alternatively, you can unpack it by putting * before map(...) like the following
[*map(...)]
or
{*map(...)}
Choose the output you desire, a list or a dictionary.
Another reason why you could be seeing this is that you're not evaluating the results of the map function. It returns a generator (an iterable) that evaluates your function lazily and not an actual list.
primes = [2,3,5,7]
map(print, primes) # no output, because it returns a generator
primes = [2,3,5,7]
for i in map(print, primes):
pass # prints 2,3,5,7
Alternately, you can do list(map(print, primes)) which will also force the generator to be evaluated and call the print function on each member of your list.
Related
As I am trying to get the square of all list numbers by using lambda function.
It is not giving me the correct answer. Can someone help me with this please. I don't want to use list comprehension etc.
I use Python 3.6
list1=[1,2,3,4]
x=(lambda x:2*x,list1)
print(x)
The code
I don't know if this counts as list comprehension to you, but this should work:
list1 = [1, 2, 3, 4] #your code with some more spacing
x = map(lambda x: x ** 2, list1) #see below for more on this
for i in x: #iterate through this
print(i) #and print each item in it
Map Function
The defenition at WS3Schools is:
The map() function executes a specified function for each item in a iterable. The item is sent to the function as a parameter.
You can go there for a more complete explanation, but basically, it calls the function on every item in the list, and puts what the function returns for each item into another iterable.
Given this list of tuples:
my_tuples = [(1,2), (3,4)]
and the following evaluation function:
def evaluate(item_tuple):
return item_tuple[0] * 2
Question: how can I get the list item (tuple) that has the highest evaluation value? (I'm guessing I can use a list comprehension for this)
def max_item(tuples_list, evaluation_fn):
'''Should return the tuple that scores max using evaluation_fn'''
# TODO Implement
# This should pass
assertEqual((3,4), max_item(my_tuples, evaluate))
Correct me if I'm wrong, you want the list of tuples sorted by the result of multiplying one of the values inside the tuple with x (in your example above it would be the first value of the tuple multiplied by 2).
If so, you can do it this way:
from operator import itemgetter
sorted(l, key=itemgetter(0 * 2), reverse=True)
I managed to do it this way:
def max_item(tuples_list, evaluation_fn):
zipped = zip(map(evaluation_fn, tuples_list), tuples_list)
return max(zipped, key=lambda i:i[0])[1]
I don't know if there's a simpler (more pythonic?) way to solve it though.
Edit
I figured how I could use a list comprehension to make it more succinct/readable:
def max_item(tuples_list, evaluation_fn):
return max([(evaluation_fn(i), i) for i in tuples_list])[1]
So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible.
a = [[1,2],[3,4]]
def cord():
return 1, 1
def printa(y,x):
print a[y][x]
printa(cord())
...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elegant. I could also rewrite the last line as "printa(cord()[0], cord()[1])", but that would execute cord() twice.
Is there an elegant, efficient way to do this? Or should I just see that quote about premature optimization and forget about this?
printa(*cord())
The * here is an argument expansion operator... well I forget what it's technically called, but in this context it takes a list or tuple and expands it out so the function sees each list/tuple element as a separate argument.
It's basically the reverse of the * you might use to capture all non-keyword arguments in a function definition:
def fn(*args):
# args is now a tuple of the non-keyworded arguments
print args
fn(1, 2, 3, 4, 5)
prints (1, 2, 3, 4, 5)
fn(*[1, 2, 3, 4, 5])
does the same.
Try this:
>>> def cord():
... return (1, 1)
...
>>> def printa(y, x):
... print a[y][x]
...
>>> a=[[1,2],[3,4]]
>>> printa(*cord())
4
The star basically says "use the elements of this collection as positional arguments." You can do the same with a dict for keyword arguments using two stars:
>>> a = {'a' : 2, 'b' : 3}
>>> def foo(a, b):
... print a, b
...
>>> foo(**a)
2 3
Actually, Python doesn't really return multiple values, it returns one value which can be multiple values packed into a tuple. Which means that you need to "unpack" the returned value in order to have multiples.
A statement like
x,y = cord()
does that, but directly using the return value as you did in
printa(cord())
doesn't, that's why you need to use the asterisk. Perhaps a nice term for it might be "implicit tuple unpacking" or "tuple unpacking without assignment".
Given the following:
(I) a = map(function, sequence)
(II) a = [function(x) for x in sequence]
When would I need to use (I)? Why choose a map object over a list when the latter is subscriptable and IMO more readable?
Also, could someone explain line 6 of the following code (Python 3):
>>>import math
>>>a = map(int,str(math.factorial(100)))
>>>sum(a)
648
>>>sum(a)
0
Why is the sum of the map object changing?
When would I need to use (I)? Why choose a map object over a list when the latter is subscriptable and IMO more readable?
map was introduced in Python 1.0, while list comprehension was not introduced until Python 2.0.
For Python 2+, you never need to use one or the other.
Reasons for still using map could include:
preference. You prefer list comprehension, not everyone agrees.
familiarity. map is very common across languages. If Python's not your native language, "map" is the function you'll look up.
brevity. map is often shorter. Compare map and lambda f,l: [f(x) for x in l].
I is an iterator -- it creates a stream of values which then vanish. II is a list -- it lasts for a while and has lots of features, like len(mylist) and mylist[-3:].
The sum changes because the iterator vanishes after you use it.
Use lists and list comprehensions. If you process tons of data, then iterators (and generators, and generator comprehensions) are awesome, but they can be confusing.
Or, use an iterator and convert into a list for further processing:
a = list( map(int,str(math.factorial(100))) )
From the docs:
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel...
The sum changes to 0 because the iterator is iterated, so it becomes nothing. This is the same concept with .read() (Try calling x = open('myfile.txt'), and then type print x.read() twice.)
In order to preserve the iterable, surround it with list():
>>> import math
>>> a = map(int,str(math.factorial(100)))
>>> sum(a)
648
>>> sum(a)
0
>>> a = list(map(int,str(math.factorial(100))))
>>> sum(a)
648
>>> sum(a)
648
Example from the docs:
>>> seq = range(8)
>>> def add(x, y): return x+y
...
>>> map(add, seq, seq)
[0, 2, 4, 6, 8, 10, 12, 14]
It's my understanding that python generator expressions return lazily evaluated comprehensions, and view objects on dictionaries update when their underlying dictionary is changed.
Given the following code (Python 2.7.6 Windows):
d = {}
gt_three = (x for x in d.viewkeys() if x > 3)
print list(gt_three)
d[1] = 'one'
d[4] = 'four'
print list(gt_three)
I would expect output like:
[]
[4]
Instead, I'm receiving:
[]
[]
If I recreate the generator after adding to the dictionary, or print the view itself, I do see the expected output.
What am I not understanding about generators? I'm quite new to python.
A generator expression returns an iterator, which you can only iterate over once. Attempts to iterate over an iterator after the first time will always see it as empty.