Skip to content

Commit 8528261

Browse files
author
Kenneth Reitz
committed
Merge pull request realpython#175 from sigmavirus24/master
Add two more examples to the structure section
2 parents 93498b9 + 226ad55 commit 8528261

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

docs/writing/structure.rst

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,9 @@ One peculiarity of Python that can surprise beginners is that
389389
strings are immutable. This means that when constructing a string from
390390
its parts, it is much more efficient to accumulate the parts in a list,
391391
which is mutable, and then glue ('join') the parts together when the
392-
full string is needed.
392+
full string is needed. One thing to notice, however, is that list
393+
comprehensions are better and faster than constructing a list in a loop
394+
with calls to append().
393395

394396
**Bad**
395397

@@ -411,6 +413,28 @@ full string is needed.
411413
nums.append(str(n))
412414
print "".join(nums) # much more efficient
413415
416+
**Best**
417+
418+
.. code-block:: python
419+
420+
# create a concatenated string from 0 to 19 (e.g. "012..1819")
421+
print "".join([str(n) for n in range(20)])
422+
423+
One final thing to mention about strings is that using join() is not always
424+
best. In the instances where you are creating a new string from a pre-determined
425+
number of strings, using the addition operator is actually faster, but in cases
426+
like above or in cases where you are adding to an existing string, using join()
427+
should be your preferred method.
428+
429+
.. code-block:: python
430+
431+
foo = 'foo'
432+
bar = 'bar'
433+
434+
foobar = foo + bar # This is good
435+
foo += 'ooo' # This is bad, instead you should do:
436+
foo = ''.join([foo, 'ooo'])
437+
414438
Vendorizing Dependencies
415439
------------------------
416440

0 commit comments

Comments
 (0)