A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/append-extend-python/ below:

Difference between append() and extend() in Python

Difference between append() and extend() in Python

Last Updated : 13 Dec, 2024

extend() and append() are two Python list methods used to add elements to a list but they behave quite differently. The append() adds a single item or any object, while extend() adds each element of an iterable to the list. 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.

append() Method

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.

List.append Example: 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

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.

List.extend Example: 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() Feature append() extend() Purpose Adds a single element to the end of the list. Adds multiple elements from an iterable to the end of the list. Argument Type Accepts a single element (any data type). Accepts an iterable (e.g., list, tuple). Resulting List Length increases by 1. Length increases by the number of elements in the iterable. Use Case When we want to add one item. When we want to merge another iterable into the list.

Time Complexity

O(1) , as adding a single element is a constant-time operation.

O(k), where k is the number of elements in b

Related Articles:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4