Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to use extend() in Python

Sarah Tanveer

The built-in Python function extend() adds all the elements of an iterable object or sequence to the end of a list.

Syntax

list.extend(iterable)

Parameters

This function takes a single parameter:

  1. iterable: the iterable object whose elements need to be added to a list. This object can be a set, list, tuple, dictionary, or string.

Return value

This function does not return anything.

The change is made directly to the list that calls the extend() function.

append() vs extend():

The built-in Python function append() works like extend(), but only adds a single element to the end of the list.

list.append(object)

It takes a single parameter: the element to be added at the end of the list. This function does not return anything and the change is made directly to the list that calls it.

Code

# declare list
testList = [1, 2, 3, 4]

print("Original List:\n", testList)

# declare iteratable object (set) to be added to the list
testSet = {10, 20, 30}

# add elements of testSet to end of testList
testList.extend(testSet)

print("List after adding new elements:\n", testList)

# declaring iterable object (string) to be added to the list
testStr = "Educative"

# add elemets of testStr to end of list
testList.extend(testStr)

print("List after adding new elements:\n", testList)

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring