How to use extend() in Python
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:
iterable: the iterable object whose elements need to be added to alist. 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 listtestList = [1, 2, 3, 4]print("Original List:\n", testList)# declare iteratable object (set) to be added to the listtestSet = {10, 20, 30}# add elements of testSet to end of testListtestList.extend(testSet)print("List after adding new elements:\n", testList)# declaring iterable object (string) to be added to the listtestStr = "Educative"# add elemets of testStr to end of listtestList.extend(testStr)print("List after adding new elements:\n", testList)