Open In App

Difference between append() and extend() in Python

Last Updated : 22 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The extend() and append() are two Python list methods used to add elements to a list but they behave quite differently. In this article, we’ll explore the differences between append() and extend() with examples and use cases to help us understand when to use each method.

extend() vs append()

Both append() and extend() are useful methods for adding elements to a list in Python, but they serve different purposes. The append() adds a single item or any object, while extend() adds each element of an iterable to the list.

Let’s understand the difference between these two methods which will help in efficient management of list data in Python.

append() Method

The append() method is used to add a single element to the end of a list. This element can be any data type, a number, a string, another list, or even an object.

Example: Add an item and an entire list as a single element to an existing list using the append() method.

Python
a = ['geeks', 'for']

# Append 'geeks' at the end of 'a'
a.append('geeks')
print(a)

# Append an entire list to 'a'
a.append(['a', 'coding', 'platform'])
print(a)

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

extend() Method

The extend() method is used to add all elements from an iterable (e.g., a list, tuple, or set) to the end of the current list. Unlike append(), which adds an entire iterable as a single element, extend() adds each element from the iterable to the list.

Example: Extend a given list into a existing list using Python.

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

# Add all element of 'b' at the end of 'a'
a.extend(b)
print(a)

Output
['geeks', 'for', 6, 0, 4, 1]

Note: A string is also an iterable, so if we extend a list with a string, it’ll append each character of the string to the current list. 

Key difference between append() and extend()

Here’s a table which represents the key differences between append() and extend() methods in Python for lists:

Featureappend()extend()
PurposeAdds a single element to the end of the list.Adds multiple elements from an iterable to the end of the list.
Argument TypeAccepts a single element (any data type).Accepts an iterable (e.g., list, tuple).
Resulting ListLength increases by 1.Length increases by the number of elements in the iterable.
Use CaseWhen we want to add one item.When we want to merge another iterable into the list.

To summarize:

  • We can use append() when we want to add a single element to the list.
  • We can use extend() when we want to add elements from another iterable, like a list, tuple, or string, to the list.

Related Articles:



Next Article

Similar Reads

Practice Tags :
three90RightbarBannerImg
  翻译: