Skip to content

Commit 46b5e63

Browse files
authored
add example to mutable/immutable types
added the map example, with explanation
1 parent 4a7336f commit 46b5e63

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

docs/writing/structure.rst

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -785,7 +785,12 @@ its parts, it is much more efficient to accumulate the parts in a list,
785785
which is mutable, and then glue ('join') the parts together when the
786786
full string is needed. One thing to notice, however, is that list
787787
comprehensions are better and faster than constructing a list in a loop
788-
with calls to ``append()``.
788+
with calls to ``append()``.
789+
790+
One other option is using the map function, which can 'map' a function
791+
('str') to an iterable ('range(20)'). This results in a map object,
792+
which you can then ('join') together just like the other examples.
793+
The map function can be even faster than a list comprehension in some cases.
789794

790795
**Bad**
791796

@@ -807,13 +812,21 @@ with calls to ``append()``.
807812
nums.append(str(n))
808813
print "".join(nums) # much more efficient
809814
810-
**Best**
815+
**Better**
811816

812817
.. code-block:: python
813818
814819
# create a concatenated string from 0 to 19 (e.g. "012..1819")
815820
nums = [str(n) for n in range(20)]
816821
print "".join(nums)
822+
823+
**Best**
824+
825+
.. code-block:: python
826+
827+
# create a concatenated string from 0 to 19 (e.g. "012..1819")
828+
nums = map(str, range(20))
829+
print "".join(nums)
817830
818831
One final thing to mention about strings is that using ``join()`` is not always
819832
best. In the instances where you are creating a new string from a pre-determined

0 commit comments

Comments
 (0)