(TL;DR)
Generating expressions, or genexp is a very broad subject in python, but maybe what you need is list comprehensions or listcomps, I’ll try to give an example here using the approach, with for
, with liscomps and a small sample of 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 from it only those 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 how you’d look wearing 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)
Note that to generate generating explressão, the syntax is identical to the generation of listcomps, the only difference is the use of parentheses instead of brackets, but let’s see the result:
output:
print('gen1 (genexp) : ', gen1,'\n')
gen1 (genexp) : <generator object <genexpr> at 0x7fb9f4d705c8>
Note that the result was not a list but a objeto
, this object can be 'manipulated' in several ways, we could do, for example:
print (list(gen1))
And we would get as a result exactly what we get with listcomp, i.e., [2, 10, 20, 4, 34, 14, 44, 70, 64]
, but 'kill' the generating expression and the result of the next example would generate an error.
Featuring the fifth element of genexp:
Taking into account that in the code we do not include the command of the previous topic print (list(gen1))
, we could display any element of genexp without creating an entire list.
## Apresentando o 5 elemento da gen1?
print ('Quinto elemento: ', list(gen1)[5], '\n')
Output:
Quinto elemento: 14
Showing that genexp "died" after run:
## 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 advantage of genexps?
The main advantage of genexps is that they do not create, a priori, an entire list in memory. of course in examples such as those presented here, there are no significant advantages, but suppose in the example above the source is not an internal list but rather some external artifact (a database, for example) with thousands or millions of elements, and the need was to access specific elements in the resulting (such as the fifth element, from the example), in this case, Voce would result only in genexp and not the entire list. Of course the explanation was minimalist, for a broader view, see the PEP 289.
Run the code in repl.it.