Consider the problem of extracting alphabets from a huge string.
One way to do it
''.join([c for c in hugestring if c.isalpha()])
The mechanism is clear: list comprehension generates a list of characters. The join method knows how many characters it needs to combine by referring to the length of the list.
Another way to do it
''.join(c for c in hugestring if c.isalpha())
Here, understanding the generator leads to the generator. The join method does not know how many characters it is about to join, because the generator does not have the len attribute. Thus, this connection method should be slower than the list comprehension method.
But python testing shows that it is not slower. Why is this so? Can anyone explain how the connection works on the generator.
To be clear:
sum(j for j in range(100))
no need to know 100 because it can track the total amount. He can access the next item using the following method for the generator, and then add to the total. However, since the lines are immutable, concatenating the lines would cumulatively create a new line at each iteration. So it will take a long time.
source share