append vs extend in Python

append and extent both are list methods in Python. Following are the definitions of append and extend methods.

append extend
append is basically used in Python to add one element extend is used to merge two lists or insert multiple elements in one list
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. The length of the list will increase by however many elements were in the iterable argument.
Appends object at end Extends list by appending elements from the iterable

Examples:

>>> a=[10,11,12] >>> a.append([13,14]) >>> a [10, 11, 12, [13, 14]]

>>> a=[10,11,12] >>> a.extend([13,14]) >>> a [10, 11, 12, 13, 14]

Example2:

>>> x=["a","b"] >>> x.append([1,2]) >>> x ['a', 'b', [1, 2]]

>>> x=["a","b"] >>> x.extend([1,2]) >>> x ['a', 'b', 1, 2]

Responses are currently closed, but you can trackback from your own site.

Comments are closed.

Powered by k2schools
%d bloggers like this: