Append: Adds its argument as a single element to the end of a list. The length of the list increases by one.
syntax: # Adds an object (a number, a string or a # another list) at the end of my_list my_list.append(object)
my_list = ['geeks', 'for'] my_list.append('geeks') print my_list |
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.
my_list = ['geeks', 'for', 'geeks'] another_list = [6, 0, 4, 1] my_list.append(another_list) print my_list |
Output:
['geeks', 'for', 'geeks', [6, 0, 4, 1]]
extend(): Iterates over its argument and adding each element to the list and extending the list. The length of the list increases by number of elements in it’s argument.
syntax: # Each element of an iterable gets appended # to my_list my_list.extend(iterable)
my_list = ['geeks', 'for'] another_list = [6, 0, 4, 1] my_list.extend(another_list) print my_list |
Output:
['geeks', 'for', 6, 0, 4, 1]
NOTE: A string is an iterable, so if you extend a list with a string, you’ll append each character as you iterate over the string.
my_list = ['geeks', 'for', 6, 0, 4, 1] my_list.extend('geeks') print my_list |
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 time complexity of O(k). Where k is the length of list which need to be added.
Recommended Posts:
- List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
- Python sympy | sieve.extend() method
- Python | Extend tuples by count of elements in tuple
- Extend Class Method in Python
- Python - Extend consecutive tuples
- Python | Append at front and remove from rear
- Difference Between '+' and 'append' in Python
- Python - Append Dictionary Keys and Values ( In order ) in dictionary
- numpy.append() in Python
- Python - Pandas dataframe.append()
- Python | Perform append at beginning of list
- Python | Pandas Index.append()
- Python | Pandas TimedeltaIndex.append()
- Python | Append multiple lists at once
- Python | Pandas Series.append()
- Python | Append Odd element twice
- Python | Append String to list
- Python | Append suffix/prefix to strings in list
- Python append to a file
- Append to JSON file using Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : cffjob

