

In fact, stay clear of dunder methods, and use the operators and operator functions like they were designed for. To keep things fair, all methods have a pre-copy step for the left-hand list which can be ignored.ĭO NOT USE THE DUNDER METHOD list._add_ directly in any way, shape or form. The iadd ( +=) and extend methods operate in-place, so a copy has to be generated each time before testing.

Plots have been generated using the perfplot module. There's no particular reason to prefer one over the other except as a matter of style. There's not much difference between these methods but that makes sense given they all have the same order of complexity (linear). List._iadd_, which extends the first list by the second. += when called on a list will internally call Generalize to N lists unless you manually unpack each one yourself.Ī += b and a.extend(b) are more or less equivalent for all practical purposes. This method uses Additional Unpacking Generalizations (PEP 448), but cannot You will need to from itertools import chain first.Ĭoncatenation is linear in memory, so this is the best in terms of Quadratic operation as memory has to be allocated for each step. But sum performs concatenation in a pairwise fashion, which means this is a This is a slick solution because of its succinctness. * A solution will qualify as a generalized solution if it works for an unknown number of lists (say, inside a loop or list comprehension) So while addition with + would raise a TypeError due to type mismatch: l = īecause it will first unpack the contents of the iterables and then simply create a list from the contents. List, such as my_list + list(my_tuple) + list(my_range) which is nowĮquivalent to just. This is also useful as a more readable way of summing iterables into a The upside to this approach is that you really don't need lists in order to perform it anything that is iterable will do. In unsupported versions a Synta圎rror is going to be raised.Īs with the other approaches, this too creates as shallow copy of the elements in the corresponding lists. This functionality was defined for Python 3.5, but it hasn't been backported to previous versions in the 3.x family. > joined_list = # unpack both iterables in a list literal The PEP, titled Additional Unpacking Generalizations, generally reduced some syntactic restrictions when using the starred * expression in Python with it, joining two lists (applies to any iterable) can now also be done with: > l1 = Another alternative has been introduced via the acceptance of PEP 448 which deserves mentioning.
