Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Python's list methods append and extend?

What's the difference between the list methods append() and extend()?

like image 953
Claudiu Avatar asked Oct 31 '08 05:10

Claudiu


People also ask

What's the difference between the list methods append and extend?

append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list.

What is the difference between appending a list and extending a list in Python?

What is the difference between the list methods append and extend? append adds its argument as a single element to the end of a list. The length of the list itself will increase by one. extend iterates over its argument adding each element to the list, extending the list.


1 Answers

append appends object at the end.

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

extend extends list by appending elements from the iterable.

>>> x = [1, 2, 3] >>> x.extend([4, 5]) >>> print(x) [1, 2, 3, 4, 5] 
like image 116
kender Avatar answered Oct 18 '22 11:10

kender