Please ignore secret bonuses. Secret tests do NOT award bonus. Max hw grade is 30+2 bonus efficiency

Do you need help?

Notice Board

Per partecipare al corso di Fondamenti di programmazione 2023-24 loggatevi e attivatelo nella vostra pagina dei corsi preferiti. A quel punto il corso appare nel menù personale cliccando sul proprio avatar. Per i materiali degli anni precedenti seguite lo stesso metodo.

To join the Programming/Lab 2023-24 course, log-on and select it on the my courses page. It will appear on the personal menu of your avatar. For earlier years use the same method.

Dubbio sull'utilizzo di .append() e .extend() in una lista

Fede123948 (280 points)
1 2 4
in Programmare in Python by (280 points)
Buongiorno, potete spiegarmi qual è la differenza tra il metodo .append() e il metodo .extend() quando si lavora con liste in Python?
339 views

2 Answers

p
p.lofaro (1210 points)
4 12 20
by (1.2k points)
Buongiorno,

date due liste, extend aggiunge gli elementi di una lista in un'altra mentre append aggiunge una lista dentro un'altra:

esempio

t1
Out[58]: ['a', 'b', 'c']

t2
Out[59]: ['p', 'q']

t1.append(t2)

t1
Out[61]: ['a', 'b', 'c', ['p', 'q']]

t1.extend(t2)

t1
Out[64]: ['a', 'b', 'c', 'p', 'q']

Saluti
dcorvasce (540 points)
0 0 5
by (540 points)

La documentazione ufficiale è abbastanza chiara a riguardo:

  • append(self, object, /): Add an item to the end of the list. Equivalent to a[len(a):] = [x].

  • extend(self, iterable, /): Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.

Entrambi i metodi lavorano in place modificando la lista esistente anziché ritornarne un'altra.
list1 = [0] * 4
extend_output = list1.extend([1, 2, 3])
append_output = list1.append(4)
assert extend_output is None and extend_output == append_output
assert list1 == [0] * 4 + [1, 2, 3, 4]

Un dettaglio carino, che non conoscevo prima di guardare la documentazione, è che append è un caso speciale di extend dove iterable in a[len(a):] = iterable è lista di un singolo elemento [x].