python-guide
python-guide copied to clipboard
"Mutable and Immutable Types" example
The best example in the Mutable and Immutable Types section of the Structuring Your Project page is:
# create a concatenated string from 0 to 19 (e.g. "012..1819")
nums = [str(n) for n in range(20)]
print "".join(nums)
It is considered the best example for being both more efficient and succinct.
Would this be a better example to use?
''.join(map(str, range(20)))
It's more succinct and is faster:
$ python -m timeit "nums = [str(n) for n in range(20)]; ''.join(nums)"
100000 loops, best of 3: 6.84 usec per loop
$ python -m timeit "''.join(map(str, range(20)))"
100000 loops, best of 3: 4.93 usec per loop
Although map looks elegant in this particular case and is indeed faster, list comprehensions are more versatile. Elegance of map may degrade quickly in some relatively common and simple cases, e.g. when you use it to access object's attributes or perform several simple operations. Also it is important to introduce list comprehensions to the reader and it seems like a good place to do so.
Having that said, I think it would be nice to have both map and list comprehension, as map fits this example really nice.
I think list comprehension is more readable and faster than map-filter one. Have a look of what Guido say about this here.
Also using xrange
instead of range
benchmark of mine is somewhat different :
$ python -m timeit "nums = [str(n) for n in xrange(20)]; ''.join(nums)"
100000 loops, best of 3: 2.9 usec per loop
$ python -m timeit "''.join(map(str, xrange(20)))"
100000 loops, best of 3: 2.11 usec per loop
Have we reached a consensus here? Do we need to change anything or is it ok the way it is right now?
@kuyan @kennethreitz since this has been merged into master on PR #797 it would make sense to close this issue, correct?
Check this one...python mutability and immutability