What's the difference between the list methods append()
and extend()
?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Append a dictionary to another one:
The method "append" adds its parameter as a single element to the list, while "extend" gets a list and adds its content.
For example,
The following two snippets are semantically equivalent:
and
The latter may be faster as the loop is implemented in C.
You can use "+" for returning extend, instead of extending in place.
Similarly
+=
for in place behavior, but with slight differences fromappend
&extend
. One of the biggest differences of+=
fromappend
andextend
is when it is used in function scopes, see this blog post.append() method will add the argument passed to it as a single element.
extend () will iterated over the arguments passed and extend the list by passing each elements iterated, basically it will add multiple elements not adding whole as one.
extend()
can be used with an iterator argument. Here is an example. You wish to make a list out of a list of lists this way:From
you want
You may use
itertools.chain.from_iterable()
to do so. This method's output is an iterator. Its implementation is equivalent toBack to our example, we can do
and get the wanted list.
Here is how equivalently
extend()
can be used with an iterator argument: