python-guide icon indicating copy to clipboard operation
python-guide copied to clipboard

"Mutable and Immutable Types" example

Open ghost opened this issue 11 years ago • 5 comments

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

ghost avatar Jul 30 '13 20:07 ghost

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.

artem-bez avatar Aug 25 '13 17:08 artem-bez

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

toanant avatar May 18 '15 07:05 toanant

Have we reached a consensus here? Do we need to change anything or is it ok the way it is right now?

userlerueda avatar Feb 09 '17 03:02 userlerueda

@kuyan @kennethreitz since this has been merged into master on PR #797 it would make sense to close this issue, correct?

userlerueda avatar Feb 23 '17 18:02 userlerueda

Check this one...python mutability and immutability

allenmarsh avatar Oct 02 '18 10:10 allenmarsh