( TL; DR )
Generating expressions, or genexp is a very broad subject in python, but maybe what you need is from list comprehensions or listcomps, I'll try to give you an example here using the for
, liscomps, and a small sample of the genexps.
Let's say we have a list of numbers:
[1,2,5,10,20,4,5,7.18,55,34,14,44,89,70,64]
and we need to extract only divisible by 2. The first option would be:
Approach with for:
lst1 = [1,2,5,10,20,4,5,7.18,55,34,14,44,89,70,64]
lst2 = []
for number in lst1:
if number%2==0:
lst2.append(number)
Output:
print (lst2)
[2, 10, 20, 4, 34, 14, 44, 70, 64]
Now let's see what it would look like using listcomps.
Using listcomps:
## Usando listcomps ##
listcomps1 = [number for number in lst1 if number%2==0]
Output:
print('listcomps1 (listcomps) :',listcomps1,'\n')
listcomps1 (listcomps) : [2, 10, 20, 4, 34, 14, 44, 70, 64]
Using genexp:
## Usando Expressões geradoras ##
gen1 = (number for number in lst1 if number%2==0)
In order to generate generative explanation, the syntax is identical to the listcomps generation, the only difference is the use of parentheses instead of brackets, but we will see the result:
output:
print('gen1 (genexp) : ', gen1,'\n')
gen1 (genexp) : <generator object <genexpr> at 0x7fb9f4d705c8>
See that the result was not a list but a objeto
, this object could be 'manipulated' in several ways, we could do, for example:
print (list(gen1))
And we would get exactly what we get with listcomp, that is, [2, 10, 20, 4, 34, 14, 44, 70, 64]
, but we 'kill' the generating expression and the result of the next example would generate an error.
Introducing the fifth element of genexp:
Considering that in the code, we did not include the command of the previous topic print (list(gen1))
, we could present any element of genexp without creating a whole list.
## Apresentando o 5 elemento da gen1?
print ('Quinto elemento: ', list(gen1)[5], '\n')
Output:
Quinto elemento: 14
Showing that genexp "died" after execution:
## Mostrando que a gen1 foi executada e "morreu": ##
print ('O que aconteceu com gen1: ', list(gen1))
Output:
O que aconteceu com gen1: []
So what's the benefit of genexps?
The main advantage of genexps is that they do not create, a priori, a whole list in memory. Of course, in examples like those presented here, there are no significant advantages, but suppose that in the above example the source is not an internal list but some external artifact (a database, for example) with thousands or millions of elements, and the need was to access specific elements in the result (like the fifth element, of the example), in this case, you would have only genexp and not the entire list. Of course the explanation was minimalist, for a broader view, see PEP 289 .
Run the code on repl.it.