Online Tutorials & Training Materials | STechies.com
Register Login

append() and extend() in Python

|| 0

append() and extend() in Python
Stechies

Both append() & extends() functions are used for string manipulation, i.e. adding a new element to the list. But they have different behavior.

Note: Both the function (append & extend) works with a number, strin, list, tuple, set, dict.

append() in Python

This function adds a single or group of elements at the end of a list as a single object. The length of the list increases by one.

Example of append() in Python:

# Python program to explain append function

# Initialize string

mylist = [1,2,3]

print("Orignal list: ",mylist);

mylist.append([8,4])

print("Append list: ",mylist)

# Append single object

mylist = [1,2,3]

mylist.append(4)

print("Append single object: ",mylist)

# Append list with tuple

mylist = [1,2,3]

mylist.append(("apple", "banana", "cherry"))

print("Append tuple: ",mylist)

# Append list with set

mylist = [1,2,3]

mylist.append({"apple", "banana", "cherry"})

print("Append set: ",mylist)

# Append list to empty list

mylist = []

mylist.append(["apple", "banana", "cherry"])

print("Append to empty list: ",mylist)

Output:

Orignal list: [1, 2, 3]

Append list: [1, 2, 3, [8, 4]]

Append single object: [1, 2, 3, 4]

Append tuple: [1, 2, 3, ('apple', 'banana', 'cherry')]

Append set: [1, 2, 3, {'apple', 'banana', 'cherry'}]

Append to empty list: [['apple', 'banana', 'cherry']]

extends() in Python:

extends() function takes an argument from the iterable (strin, list, tuple, set, dict) and add each elements at the end of the list. The length of the final list increases by the number of elements present in the iterable argument.

Example of extend() in Python:

# Python program to explain Extend function

# Initialize string

mylist = [1,2,3]

print("Orignal list: ",mylist);

# Extend list with list

mylist.extend([8,4])

print("Append list: ",mylist)

# Extend list with tuple

mylist = [1,2,3]

mylist.extend(("apple", "banana", "cherry"))

print("Append tuple: ",mylist)

# Extend list with Set

mylist = [1,2,3]

mylist.extend({"apple", "banana", "cherry"})

print("Append set: ",mylist)

Output:

Original list: [1, 2, 3]

Append list: [1, 2, 3, 8, 4]

Append tuple: [1, 2, 3, 'apple', 'banana', 'cherry']

Append set: [1, 2, 3, 'cherry', 'apple', 'banana']

Note: extend() function won't work with a single object.

Difference Between append() and extend()

Here are some basic difference between append() and extend() in Python:

  • append() takes single element as an argument whereas extend() doesn't take single element as an argument
  • append() adds all argument as a single element to the end of a list whereas extend()  iterates over the argument and add each element of argument at the end of the list.
  • append() increases the size of list by 1 whereas extend() increases the size of the list by the number of elements in the iterable argument.