4 ms·
Huh. Never seen that. But without the [] it appears to produce a generator expression (which is immediately consumed) rather than a list (which is immediately
by a3n 10y ago
Huh. Never seen that.
But without the [] it appears to produce a generator expression (which is immediately consumed) rather than a list (which is immediately consumed).
In [9]: print ' '.join(str(x) for x in range(3))
0 1 2
In [10]: type(str(x) for x in range(3))
Out[10]: generator
In [11]: type([str(x) for x in range(3)])
Out[11]: list
Same effect between the two, but different and interesting things. Thanks.
EDIT: Also:
In [3]: %timeit ' '.join(str(x) for x in range(3))
100000 loops, best of 3: 3.11 µs per loop
In [4]: %timeit ' '.join([str(x) for x in range(3)])
1000000 loops, best of 3: 1.47 µs per loop
The list version, with the [], is about twice as fast as the generator version (without the brackets). I suspect because the generator version has to "go back to the well" for each value, but I don't really know. And this is one small test case, maybe it's different for larger sequences. Testing is everything. :)
- gspetr 10y agoI'll refer you to the original source where I picked up this trick: http://chimera.labs.oreilly.com/books/1230000000393/ch01.html#generatorargs http://chimera.labs.oreilly.com/books/1230000000393/ch01.htm... "Transforming and Reducing Data at the Same Time" I highly recommend David Beazley's excellent book, it made me a much better Python developer, helping me produce both idiomatic and efficient solutions over the last year. That book is programming poetry.
- a3n 10y agoThanks for that. Looks good so far.