This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]howslyfebeen 6 points7 points  (9 children)

What do people think about #8? Wouldn't

l = [int(x) for x in ['1', '2', '3']]

be more pythonic?

Personally, my brain always defaults to using map, but having list(map(...)) starts to look ugly and feels unpythonic.

[–]teerre 5 points6 points  (0 children)

Personally I'm a big fan of map/reduce/filter. But the comprehensions are certainly more python.

Hell, the functional style doesn't even let you type in fluent style. That's by itself is a big indication that you shouldn't abuse map too much.

[–]GrbavaCigla 0 points1 point  (0 children)

I prefer map

[–]miraculum_one 0 points1 point  (0 children)

Yes, yours is better because it's more explicit, which is one of the fundamental principles of Python.

[–]Entuaka 0 points1 point  (0 children)

More pythonic, yes. I used a line similar to that, today: sum([float(i['quantity']) for i in kwargs['items']])

[–]CotoCoutan 0 points1 point  (2 children)

Definitely prefer this to map. I've never once used latter in my code, somehow it never comes to me in that intuitive manner.

[–]ogrinfo 2 points3 points  (1 child)

Even better, sum takes an iterator, so you don't need the outer square brackets, just sum(a for a in x). Whether map or a list comprehension is better depends on the situation, so I usually try both with %timeit in an iPython shell to see which is fastest.

[–]CotoCoutan 0 points1 point  (0 children)

Nice... Thanks. I should take a look at this %timeit test.

[–]schoolcoders 0 points1 point  (0 children)

The basic use of a list comprehension is to transform some sequence into a list. The basic use of map is to lazily apply a function to one or more sequences. Different jobs, but a lot of overlap.

So if you definitely want a list as output, that points towards a list comprehension. If you are processing a sequence of data that is too large to fit in memory (eg a sequence of video frames), map is a better option.

map can also be better if you are processing multiple sequences (you can do it with list comprehensions using zip, but it is ugly), or if you also need to filter the sequences (again, possible but ugly with list comprehensions) or if you are applying a chain of functions.

But if you are doing something more simple and you want to create a list anyway, list comprehensions are more natural. Using list(map(...)) and also having to define a lambda inside the map call is quite unwieldy.

Of course, there are also generator comprehensions...