In earlier versions of Python, the idea of ββunderstanding lists was implemented to put together these two code templates:
results = []
for item in somelist:
if sometest(item):
results.add(item)
and
results = []
for item in somelist:
results.add(2 * item)
adding a new syntax that includes doing all three things in one - changing elements and / or testing them to include only some of the results and create a list of results:
results = [2 * item for item in somelist if sometest(item)]
[], "" Python, .
, , Python - , , , , , .
, -, () [], :
somelist = [1,2,3,4,5]
results = (2 * item for item in somelist if sometest(item))
, :
function((2 * item for item in somelist))
, :
function(2 * item for item in somelist)
, for , .
, :
>>> print (item for item in [1,2,3])
<generator object <genexpr> at 0x7fe31b8663c0>
, , Python 2.x, , , ^^ - , .
:
>>> print [item for item in [1,2,3]]
[1,2,3]
, - , , , .
- ( , , , , -).