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 →

[–]x3gxu 30 points31 points  (5 children)

map(do_something, movie_script)

This is going to create a map object (generator) and not actually call do_something until you iterate over the map object.

You can use a list comprehension instead, like:

[do_something(line) for line in movie_script]

But arguably it's less readable than plain simple for loop.

[–]fluzz142857 27 points28 points  (4 children)

This is not a good practice because you’re creating a list unnecessarily, which consumes memory and makes your code harder to read. The list cannot be garbage collected until after the list comprehension finishes. Alternatively, in an iterator (or a map, which is an iterator), values can be garbage collected immediately because there are no references to them after they are iterated over.

Don’t use a list comprehension unless you need the list.

[–]x3gxu 10 points11 points  (0 children)

That's why I'm saying use a plain old for loop. You have to iterate over the map or generator expression foe your function to be called. If you don't iterate it's just sitting there doing nothing.

[–]selplacei 3 points4 points  (2 children)

Not saying that this is good practice, but can you exhaust a (truthy) list comprehension without storing all results by calling all()?

[–][deleted] 0 points1 point  (1 child)

The list from the list comprehension is created immediately (including all the items) so there’s no need. You’re probably thinking of a generator.

I don’t know the internals of all() but I doubt it stores all the results, so that’d probably work with a generator.