DEV Community

Cover image for Difference between append() and extend() in Python
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

Difference between append() and extend() in Python

append() and extend() are two list methods used to add elements to a list, but they behave differently.

append() adds a single item (of any type) to the end of a list.
extend() adds all elements from an iterable (like a list, tuple, or set) to the end of the current list.

append() Method

append() method adds a single element to the end of a list. This element can be a number, string, list, or any object.

a = ['geeks', 'for']

a.append('geeks')
print(a)

a.append(['a', 'coding', 'platform'])
print(a)
Enter fullscreen mode Exit fullscreen mode

Output

['geeks', 'for', 'geeks']
['geeks', 'for', 'geeks', ['a', 'coding', 'platform']]

Enter fullscreen mode Exit fullscreen mode

extend() Method

extend() method adds all elements from an iterable to the end of the current list. Unlike append(), it does not add the iterable as a single element; instead, each element is added individually.

a = ['geeks', 'for']
b = [6, 0, 4, 1]

a.extend(b)
print(a)
Enter fullscreen mode Exit fullscreen mode

Output

['geeks', 'for', 6, 0, 4, 1]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)