Pergunta

Qual é a diferença entre os métodos de lista append() e extend()?

Foi útil?

Solução

append: Anexos objeto no final.

x = [1, 2, 3]
x.append([4, 5])
print (x)

da-te: [1, 2, 3, [4, 5]]


extend: Estende a lista anexando elementos do iterable.

x = [1, 2, 3]
x.extend([4, 5])
print (x)

da-te: [1, 2, 3, 4, 5]

Outras dicas

append adiciona um elemento a uma lista e extend Concatena a primeira lista com outra lista (ou outro iterável, não necessariamente uma lista.)

>>> li = ['a', 'b', 'mpilgrim', 'z', 'example']
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']

>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new']

>>> li.append(["new", 2])
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new', ['new', 2]]

>>> li.insert(2, "new")
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2]]

>>> li.extend(["two", "elements"])
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2], 'two', 'elements']

A partir de Mergulhe em python.

Qual é a diferença entre os métodos de lista anexar e estender?

  • append adiciona seu argumento como um único elemento ao final de uma lista.O comprimento da lista aumentará em um.
  • extend itera sobre seu argumento adicionando cada elemento à lista, estendendo a lista.O comprimento da lista aumentará de acordo com o número de elementos no argumento iterável.

append

O list.append O método anexa um objeto ao final da lista.

my_list.append(object) 

Qualquer que seja o objeto, seja um número, uma string, outra lista ou qualquer outra coisa, ele é adicionado ao final de my_list como uma única entrada na lista.

>>> my_list
['foo', 'bar']
>>> my_list.append('baz')
>>> my_list
['foo', 'bar', 'baz']

Portanto, lembre-se de que uma lista é um objeto.Se você anexar outra lista a uma lista, a primeira lista será um único objeto no final da lista (que pode não ser o que você deseja):

>>> another_list = [1, 2, 3]
>>> my_list.append(another_list)
>>> my_list
['foo', 'bar', 'baz', [1, 2, 3]]
                     #^^^^^^^^^--- single item at the end of the list.

extend

O list.extend O método estende uma lista anexando elementos de um iterável:

my_list.extend(iterable)

Assim, com extensão, cada elemento do iterável é anexado à lista.Por exemplo:

>>> my_list
['foo', 'bar']
>>> another_list = [1, 2, 3]
>>> my_list.extend(another_list)
>>> my_list
['foo', 'bar', 1, 2, 3]

Lembre-se de que uma string é iterável, portanto, se você estender uma lista com uma string, você acrescentará cada caractere à medida que iterar sobre a string (o que pode não ser o que você deseja):

>>> my_list.extend('baz')
>>> my_list
['foo', 'bar', 1, 2, 3, 'b', 'a', 'z']

Sobrecarga do Operador, __add__ (+) e __iadd__ (+=)

Ambos + e += operadores são definidos para list.Eles são semanticamente semelhantes para estender.

my_list + another_list cria uma terceira lista na memória, para que você possa retornar o resultado dela, mas exige que o segundo iterável seja uma lista.

my_list += another_list modifica a lista no local (é é o operador no local e as listas são objetos mutáveis, como vimos), portanto, não cria uma nova lista.Também funciona como estender, pois o segundo iterável pode ser qualquer tipo de iterável.

Não fique confuso - my_list = my_list + another_list não é equivalente a += - fornece uma nova lista atribuída a my_list.

Complexidade de tempo

Anexar tem complexidade de tempo constante, O(1).

Estender tem complexidade de tempo, O(k).

Iterando através de múltiplas chamadas para append aumenta a complexidade, tornando-o equivalente ao de extensão, e como a iteração de extensão é implementada em C, sempre será mais rápida se você pretende anexar itens sucessivos de um iterável a uma lista.

Desempenho

Você pode estar se perguntando o que tem melhor desempenho, já que o acréscimo pode ser usado para obter o mesmo resultado que o prolongamento.As seguintes funções fazem a mesma coisa:

def append(alist, iterable):
    for item in iterable:
        alist.append(item)

def extend(alist, iterable):
    alist.extend(iterable)

Então vamos cronometrá-los:

import timeit

>>> min(timeit.repeat(lambda: append([], "abcdefghijklmnopqrstuvwxyz")))
2.867846965789795
>>> min(timeit.repeat(lambda: extend([], "abcdefghijklmnopqrstuvwxyz")))
0.8060121536254883

Respondendo a um comentário sobre horários

Um comentarista disse:

Resposta perfeita, só sinto falta do momento de comparar adicionando apenas um elemento

Faça a coisa semanticamente correta.Se você quiser anexar todos os elementos em um iterável, use extend.Se você estiver apenas adicionando um elemento, use append.

Ok, então vamos criar um experimento para ver como isso funciona com o tempo:

def append_one(a_list, element):
    a_list.append(element)

def extend_one(a_list, element):
    """creating a new list is semantically the most direct
    way to create an iterable to give to extend"""
    a_list.extend([element])

import timeit

E vemos que sair do nosso caminho para criar um iterável apenas para usar extend é uma (pequena) perda de tempo:

>>> min(timeit.repeat(lambda: append_one([], 0)))
0.2082819009956438
>>> min(timeit.repeat(lambda: extend_one([], 0)))
0.2397019260097295

Aprendemos com isso que não há nada a ganhar com o uso extend quando temos apenas um elemento a ser anexado.

Além disso, esses horários não são tão importantes.Estou apenas mostrando a eles que, em Python, fazer a coisa semanticamente correta é fazer as coisas que Certo Caminho™.

É concebível que você teste os tempos em duas operações comparáveis ​​e obtenha um resultado ambíguo ou inverso.Concentre-se apenas em fazer a coisa semanticamente correta.

Conclusão

Nós vemos que extend é semanticamente mais claro e pode ser executado muito mais rápido do que append, quando você pretende anexar cada elemento em um iterável a uma lista.

Se você tiver apenas um único elemento (não iterável) para adicionar à lista, use append.

append Anexa um único elemento. extend Anexa uma lista de elementos.

Observe que, se você passar em uma lista para anexar, ela ainda adicionará um elemento:

>>> a = [1, 2, 3]
>>> a.append([4, 5, 6])
>>> a
[1, 2, 3, [4, 5, 6]]

Os dois trechos a seguir são semanticamente equivalentes:

for item in iterator:
    a_list.append(item)

e

a_list.extend(iterator)

O último pode ser mais rápido à medida que o loop é implementado em C.

o append() O método adiciona um único item ao final da lista.

x = [1, 2, 3]
x.append([4, 5])
x.append('abc')
print(x)
# gives you
[1, 2, 3, [4, 5], 'abc']

o extend() O método pega um argumento, uma lista e anexa cada um dos itens do argumento à lista original. (As listas são implementadas como classes. "Criar" uma lista está realmente instanciando uma classe. Como tal, uma lista possui métodos que operam nela.)

x = [1, 2, 3]
x.extend([4, 5])
x.extend('abc')
print(x)
# gives you
[1, 2, 3, 4, 5, 'a', 'b', 'c']

A partir de Mergulhe em python.

You can use "+" for returning extend, instead of extending in place.

l1=range(10)

l1+[11]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]

l2=range(10,1,-1)

l1+l2

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2]

Similarly += for in place behavior, but with slight differences from append & extend. One of the biggest differences of += from append and extend is when it is used in function scopes, see this blog post.

Append vs Extend

enter image description here

With append you can append a single element that will extend the list:

>>> a = [1,2]
>>> a.append(3)
>>> a
[1,2,3]

If you want to extend more than one element you should use extend, because you can only append one elment or one list of element:

>>> a.append([4,5])
>>> a
>>> [1,2,3,[4,5]]

So that you get a nested list

Instead with extend you can extend a single element like this

>>> a = [1,2]
>>> a.extend([3])
>>> a
[1,2,3]

Or, differently from append, extend more elements in one time without nesting the list into the original one (that's the reason of the name extend)

>>> a.extend([4,5,6])
>>> a
[1,2,3,4,5,6]

Adding one element with both methods

enter image description here

append 1 element

>>> x = [1,2]
>>> x.append(3)
>>> x
[1,2,3]

extend one element

>>> x = [1,2]
>>> x.extend([3])
>>> x
[1,2,3,4]

Adding more elements... with different results

If you use append for more than one element, you have to pass a list of elements as arguments and you will obtain a NESTED list!

>>> x = [1,2]
>>> x.append([3,4])
>>> x
[1,2,[3,4]]

With extend, instead, you pass a list as argument, but you will obtain a list with the new element that are not nested in the old one.

>>> z = [1,2] 
>>> z.extend([3,4])
>>> z
[1,2,3,4]

So, with more elements, you will use extend to get a list with more items. You will use append, to append not more elements to the list, but one element that is a nested list as you can clearly see in the output of the code.

enter image description here

enter image description here

append(object) - Updates the list by adding an object to the list.

x = [20]
# List passed to the append(object) method is treated as a single object.
x.append([21, 22, 23])
# Hence the resultant list length will be 2
print(x)
--> [20, [21, 22, 23]]

extend(list) - Essentially concatenates two lists.

x = [20]
# The parameter passed to extend(list) method is treated as a list.
# Eventually it is two lists being concatenated.
x.extend([21, 22, 23])
# Here the resultant list's length is 4
print(x)
[20, 21, 22, 23]

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

list2d = [[1,2,3],[4,5,6], [7], [8,9]]

you want

>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]

You may use itertools.chain.from_iterable() to do so. This method's output is an iterator. Its implementation is equivalent to

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

Back to our example, we can do

import itertools
list2d = [[1,2,3],[4,5,6], [7], [8,9]]
merged = list(itertools.chain.from_iterable(list2d))

and get the wanted list.

Here is how equivalently extend() can be used with an iterator argument:

merged = []
merged.extend(itertools.chain.from_iterable(list2d))
print(merged)
>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]

This is the equivalent of append and extend using the + operator:

>>> x = [1,2,3]
>>> x
[1, 2, 3]
>>> x = x + [4,5,6] # Extend
>>> x
[1, 2, 3, 4, 5, 6]
>>> x = x + [[7,8]] # Append
>>> x
[1, 2, 3, 4, 5, 6, [7, 8]]

append(): It is basically used in Python to add one element.

Example 1:

>> a = [1, 2, 3, 4]
>> a.append(5)
>> print(a)
>> a = [1, 2, 3, 4, 5]

Example 2:

>> a = [1, 2, 3, 4]
>> a.append([5, 6])
>> print(a)
>> a = [1, 2, 3, 4, [5, 6]]

extend(): Where extend(), is used to merge two lists or insert multiple elements in one list.

Example 1:

>> a = [1, 2, 3, 4]
>> b = [5, 6, 7, 8]
>> a.extend(b)
>> print(a)
>> a = [1, 2, 3, 4, 5, 6, 7, 8]

Example 2:

>> a = [1, 2, 3, 4]
>> a.extend([5, 6])
>> print(a)
>> a = [1, 2, 3, 4, 5, 6]

An interesting point that has been hinted, but not explained, is that extend is faster than append. For any loop that has append inside should be considered to be replaced by list.extend(processed_elements).

Bear in mind that apprending new elements might result in the realloaction of the whole list to a better location in memory. If this is done several times because we are appending 1 element at a time, overall performance suffers. In this sense, list.extend is analogous to "".join(stringlist).

Append adds the entire data at once. The whole data will be added to the newly created index. On the other hand, extend, as it name suggests, extends the current array.

For example

list1 = [123, 456, 678]
list2 = [111, 222]

With append we get:

result = [123, 456, 678, [111, 222]]

While on extend we get:

result = [123, 456, 678, 111, 222]

An English dictionary define the words append and extend as:

append: add (something) to the end of a written document.
extend: make larger. Enlarge or expand


With that knowledge, now let's understand

1) The difference between append and extend

append:

  • Appends any Python object as-is to the end of the list (i.e. as a last element in the list).
  • The resulting list may be nested and contain heterogeneous elements (i.e. list, string, tuple, dictionary, set, etc.)

extend:

  • Accepts any iterable as its argument and makes the list larger.
  • The resulting list is always one dimensional list (i.e. no nesting) and it may contain heterogeneous elements in it (e.g. characters, integers, float) as a result of applying list(iterable).

2) Similarity between append and extend

  • Both takes exactly one argument.
  • Both modify the list in-place.
  • As a result, both returns None.

Example

lis = [1, 2, 3]

# 'extend' is equivalent to this
lis = lis + list(iterable)

# 'append' simply appends its argument as the last element to the list
# as long as the argument is a valid Python object
lis.append(object)

I hope I can make a useful supplement to this question. If your list stores a specific type object, for example Info, here is a situation that extend method is not suitable: In a for loop and and generating an Info object every time and using extend to store it into your list, it will fail. The exception is like below:

TypeError: 'Info' object is not iterable

But if you use the append method, the result is OK. Because every time using the extend method, it will always treat it as a list or any other collection type, iterate it, and place it after the previous list. A specific object can not be iterated, obviously.

To distinguish them intuitively

l1 = ['a', 'b', 'c']
l2 = ['d', 'e', 'f']
l1.append(l2)
l1
['a', 'b', 'c', ['d', 'e', 'f']]

It's like l1 reproduce a body inside her body(nested).

# Reset l1 = ['a', 'b', 'c']
l1.extend(l2)
l1
['a', 'b', 'c', 'd', 'e', 'f']

It's like that two separated individuals get married and construct an united family.

Besides I make an exhaustive cheatsheet of all list's methods for your reference.

list_methods = {'Add': {'extend', 'append', 'insert'},
                'Remove': {'pop', 'remove', 'clear'}
                'Sort': {'reverse', 'sort'},
                'Search': {'count', 'index'},
                'Copy': {'copy'},
                }

extend(L) extends the list by appending all the items in the given list L.

>>> a
[1, 2, 3]
a.extend([4])  #is eqivalent of a[len(a):] = [4]
>>> a
[1, 2, 3, 4]
a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a[len(a):] = [4]
>>> a
[1, 2, 3, 4]

append "extends" the list (in place) by only one item, the single object passed (as argument).

extend "extends" the list (in place) by as many items as the object passed (as argument) contains.

This may be slightly confusing for str objects.

  1. If you pass a string as argument: append will add a single string item at the end but extend will add as many "single" 'str' items as the length of that string.
  2. If you pass a list of strings as argument: append will still add a single 'list' item at the end and extend will add as many 'list' items as the length of the passed list.
def append_o(a_list, element):
    a_list.append(element)
    print('append:', end = ' ')
    for item in a_list:
        print(item, end = ',')
    print()

def extend_o(a_list, element):
    a_list.extend(element)
    print('extend:', end = ' ')
    for item in a_list:
        print(item, end = ',')
    print()
append_o(['ab'],'cd')

extend_o(['ab'],'cd')
append_o(['ab'],['cd', 'ef'])
extend_o(['ab'],['cd', 'ef'])
append_o(['ab'],['cd'])
extend_o(['ab'],['cd'])

produces:

append: ab,cd,
extend: ab,c,d,
append: ab,['cd', 'ef'],
extend: ab,cd,ef,
append: ab,['cd'],
extend: ab,cd,

Append and extend are one of the extensibility mechanisms in python.

Append: Adds an element to the end of the list.

my_list = [1,2,3,4]

To add a new element to the list, we can use append method in the following way.

my_list.append(5)

The default location that the new element will be added is always in the (length+1) position.

Insert: The insert method was used to overcome the limitations of append. With insert, we can explicitly define the exact position we want our new element to be inserted at.

Method descriptor of insert(index, object). It takes two arguments, first being the index we want to insert our element and second the element itself.

Example: my_list = [1,2,3,4]
my_list[4, 'a']
my_list
[1,2,3,4,'a']

Extend: This is very useful when we want to join two or more lists into a single list. Without extend, if we want to join two lists, the resulting object will contain a list of lists.

a = [1,2]
b = [3]
a.append(b)
print (a)
[1,2,[3]]

If we try to access the element at pos 2, we get a list ([3]), instead of the element. To join two lists, we'll have to use append.

a = [1,2]
b = [3]
a.extend(b)
print (a)
[1,2,3]

To join multiple lists

a = [1]
b = [2]
c = [3]
a.extend(b+c)
print (a)
[1,2,3]
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top