More Python List append() Examples of
Here are some examples and use-cases of list append() function in Python.
Append to list in Python using List.append() Method
List.append() method is used to add an element to the end of a list in Python or append a list in Python, modifying the list in place. For example: `my_list.append(5)` adds the element `5` to the end of the list `my_list`.
Example: In this example, the In below code Python list append() adds a new element at the end of list.
Python
# using list fruits fruits = [ "apple" , "cherry" , "banana" ] # adding new element grapes fruits.append( "grapes" ) # priting the fruits list print (fruits) |
Output :
['apple', 'cherry', 'banana', 'grapes']
Add List to the List using Python List Append() Method
This method involves appending a list to another list in Python using the `append()` method, thereby adding the entire list as a single element to the target list.
Example: In this example, we will append a complete list at the end of the given list.
Python
# my_list my_list = [ 'geeks' , 'for' , 'geeks' ] # another list another_list = [ 6 , 0 , 4 , 1 ] # append another_list to my_list my_list.append(another_list) print (my_list) |
Output:
['geeks', 'for', 'geeks', [6, 0, 4, 1]]
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. If you want to append the elements of a list to another list you can use Python’s List extend() method.
Time complexity: O(1) or constant time. This is because lists can be accessed randomly using indexing, so the last element can be accessed easily in O(1) time.
We have discussed the definition, syntax, and examples of append() in Python. Append function is a very basic and useful operation in Python programming and should be known by every Python student.
Read Other Python List Methods
Similar Reads:
Python List append() Method
Python list append() method is used to add elements at the end of the list.
Example
Python
list = [ 2 , 5 , 6 , 7 ] list .append( 8 ) print ( list ) |
Output
[2, 5, 6, 7, 8]