File tree Expand file tree Collapse file tree 1 file changed +25
-1
lines changed
Expand file tree Collapse file tree 1 file changed +25
-1
lines changed Original file line number Diff line number Diff line change @@ -389,7 +389,9 @@ One peculiarity of Python that can surprise beginners is that
389389strings are immutable. This means that when constructing a string from
390390its parts, it is much more efficient to accumulate the parts in a list,
391391which 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
You can’t perform that action at this time.
0 commit comments