What is the most pythonic way to execute a generator expression?

More and more Python features are moving into a "lazy executable" such as an expression generator and other iterators. Sometimes, however, I see that I want to drop one β€œfor” circuit in order to perform some action.

What would be the most pythonic thing to get a loop actually executed?

For instance:

a = open("numbers.txt", "w") (a.write ("%d " % i) for i in xrange(100)) a.close() 

Do not activate the code, but you understand what I mean. If I use a list generator, instead I have the side effect of creating an N-length list filled with "No".

I am currently using an expression as an argument in a call to "any" or "all". But I would like to find a way that will not depend on the result of the expression being executed in the loop - both "any" and "all" can stop depending on the expressed expression.

To be clear, these are the ways to do this that I already know about, and each has its own drawbacks:

 [a.write ("%d " % i) for i in xrange(100))] any((a.write ("%d " % i) for i in xrange(100))) for item in (a.write ("%d " % i) for i in xrange(100)): pass 
+3
source share
3 answers

There are many accumulators that affect the use of everything iterable that they specify, for example min or max - but even they do not completely ignore the results obtained in the process ( min and max , for example, will throw an exception if some results are complex numbers). I don’t think there is a built-in storage device that does exactly what you want - you have to write (and add to your personal quiet tiny utility function) a tiny utility function such as

 def consume(iterable): for item in iterable: pass 

The main reason, I think, is that Python has a for statement, and you should use it when it fits like a glove (i.e. for cases where you want consume for ;-).

BTW, a.write returns None , which is fake, so any really consumes it (and a.writelines will do even better!). But I understand that you just cited this as an example :-).

+5
source

There is one obvious way to do this, and that is how you should do it. There is no excuse for doing this in a smart way.

 a = open("numbers.txt", "w") for i in xrange(100): a.write("%d " % i) d.close() 

Lazy execution gives you serious benefits: it allows you to transfer a sequence to another piece of code without having to store all the memory in memory. It is designed to create efficient sequences in the form of data types.

In this case, you do not need to do lazy execution. You want to perform. You can just do it. Using a for loop.

+10
source

If I wanted to make this specific example, I would write

 for i in xrange(100): a.write('%d ' % i) 

If I often needed to use an iterator for its effect, I would define

 def for_effect(iterable): for _ in iterable: pass 
+7
source

Source: https://habr.com/ru/post/1315163/


All Articles