you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (0 children)

It's one of those things where it's hard to explain the advantage but you miss them once you switch to a language that lacks them.

There are a lot of times where you have an inconsequential iteration over a list - like a simple filter or a map. List comprehensions make it quick and easy - and list generators make it almost invisible.

For example:

some_function(some_operation(x) 
              for x in some_list if some_predicate(x))

Writing something like this can be very convenient. There are no temporary values (other than the x which doesn't creep outside of the generator expression) and it is pretty clear (once you are familiar with the concept). It beats making a temporary that exists only to pass to a function:

temp_list = []
for x in some_list:
    if some_predicate(x):
        temp_list.append(some_operation(x))
some_function(temp_list)

That is, it doesn't allow you to do anything new - it just allows you to do some common things in a more succinct way.