@@ -809,16 +809,12 @@ and can be used as a key for a dictionary.
809
809
810
810
One peculiarity of Python that can surprise beginners is that
811
811
strings are immutable. This means that when constructing a string from
812
- its parts, it is much more efficient to accumulate the parts in a list,
813
- which is mutable, and then glue ('join') the parts together when the
814
- full string is needed. One thing to notice, however, is that list
815
- comprehensions are better and faster than constructing a list in a loop
816
- with calls to ``append() ``.
817
-
818
- One other option is using the map function, which can 'map' a function
819
- ('str') to an iterable ('range(20)'). This results in a map object,
820
- which you can then ('join') together just like the other examples.
821
- The map function can be even faster than a list comprehension in some cases.
812
+ its parts, appending each part to the string is inefficient because
813
+ the entirety of the string is copied on each append.
814
+ Instead, it is much more efficient to accumulate the parts in a list,
815
+ which is mutable, and then glue (``join ``) the parts together when the
816
+ full string is needed. List comprehensions are usually the fastest and
817
+ most idiomatic way to do this.
822
818
823
819
**Bad **
824
820
@@ -830,7 +826,7 @@ The map function can be even faster than a list comprehension in some cases.
830
826
nums += str (n) # slow and inefficient
831
827
print nums
832
828
833
- **Good **
829
+ **Better **
834
830
835
831
.. code-block :: python
836
832
@@ -840,20 +836,12 @@ The map function can be even faster than a list comprehension in some cases.
840
836
nums.append(str (n))
841
837
print " " .join(nums) # much more efficient
842
838
843
- **Better **
844
-
845
- .. code-block :: python
846
-
847
- # create a concatenated string from 0 to 19 (e.g. "012..1819")
848
- nums = [str (n) for n in range (20 )]
849
- print " " .join(nums)
850
-
851
839
**Best **
852
840
853
841
.. code-block :: python
854
842
855
843
# create a concatenated string from 0 to 19 (e.g. "012..1819")
856
- nums = map ( str , range (20 ))
844
+ nums = [ str (n) for n in range (20 )]
857
845
print " " .join(nums)
858
846
859
847
One final thing to mention about strings is that using ``join() `` is not always
0 commit comments