Extend and append in python
In this article, we will cover the Python List Append and Python List Extend and will try to understand the difference between Python’s list methods append and extend. Show
What is Append in Python?Python’s append() function inserts a single element into an existing list. The element will be added to the end of the old list rather than being returned to a new list. Adds its argument as a single element to the end of a list. The length of the list increases by one. Syntax of append() in Python# Adds an object (a number, a string or a # another list) at the end of my_list my_list.append(object) Example 1: Python3
Output: ['geeks', 'for', 'geeks'] NOTE: A list is an object. If you append another list onto a list, the parameter list will be a single object at the end of the list. Example 2: Python3
Output: ['geeks', 'for', 'geeks', [6, 0, 4, 1]] What is extend() in Python?Iterates over its argument and adding each element to the list and extending the list. The length of the list increases by a number of elements in its argument. Syntax of extend() in Python# Each element of an iterable gets appended # to my_list my_list.extend(iterable) Example 1: Python3
Output: ['geeks', 'for', 6, 0, 4, 1] NOTE: A string is iterable, so if you extend a list with a string, you’ll append each character as you iterate over the string. Example 2: Python3
Output: ['geeks', 'for', 6, 0, 4, 1, 'g', 'e', 'e', 'k', 's'] Time Complexity: Append has constant time complexity i.e.,O(1). Extend has a time complexity of O(k). Where k is the length of the list which need to be added. append: Appends object at end. x = [1, 2, 3] x.append([4, 5]) print (x) gives you: [1, 2, 3, [4, 5]] extend: Extends list by appending elements from the iterable. x = [1, 2, 3] x.extend([4, 5]) print (x) gives you: [1, 2, 3, 4, 5] Hope it helps!! If you need to know more about Python, It's recommended to join Python course today. Thanks!
|