In Python, elements in a list can be added using the append(element)
method. This method allows us to add elements to the end of a list easily.
In the previous articles, we explored accessing list elements by index and using the list index method to retrieve an element’s position. This article covers appending new elements to lists.
Append elements to list
List in Python is a mutable object. Mutable object means we can modify the list object. It means we can perform operations like add (append), update (change) and delete (remove) of elements in the list.
Method syntax:
list_obj.append(element)
<class 'list'>
, has providedappend(element)
method to append (add) elements in the lists. This method takes one parameter, which is the element to be added in the list.- This method is called on the list object in which we want to add the element.
- Using this method elements are added at the end of the list.
append(element)
adds a reference of object in memory, but does not create a copy of object.- We can add any element at the end of the list using append(element) method.
- We can perform this append operation on the nested list elements as well.
Now, lets see how we can use this method in programs.
Program – Append Element at the End of the List
# append element in the list using append method
sybytes_list = ['Python', 'AWS', 'Java', 'Azure']
print(sybytes_list)
sybytes_list.append("Machine Learning")
print(sybytes_list)
In this program, we have declared and initialized a list referenced by a variable sybytes_list
. We call the append()
method on this list to add the element “Machine Learning” to the end.
Output – Example Program – Append Element at the End of the List
['Python', 'AWS', 'Java', 'Azure']
['Python', 'AWS', 'Java', 'Azure', 'Machine Learning']
The program output shows the list before and after appending “Machine Learning”. The element is added to the end of the list.
Program – Append Element to a Nested List
# append element to a nested element of a list
print("append element in nested list")
nested_list = ['Python', 'AWS', 'Azure', [1, 2, 3]]
print("original nested list", nested_list)
nested_list[3].append(4) # access index 3 element and append 4 in that list element
print("changed mixed list", nested_list)
This program demonstrates how to add an element to a nested list. We declare a nested list called nested_list
, where the nested element [1, 2, 3]
is at index 3
. To add a number in this nested element, first we access this nested element and use append()
to add the number 4 to it. Since nested element is also a list that is why we are able to call append()
method on that element.
Output – Example Program – Append Element to a Nested List
append in mutable elements in list
original nested list ['Python', 'AWS', 'Azure', [1, 2, 3]]
changed mixed list ['Python', 'AWS', 'Azure', [1, 2, 3, 4]]
The output shows the nested list before and after adding the number 4
to the nested list [1, 2, 3]
. By using the append()
method, we can extend even the nested elements in the list.
Summary
In this article, we learned how to:
- Append elements to list using the
append()
method - Add elements at the end of the list
- Use
append()
to append element to a nested list in Python
Code snippets and programs related to Append Elements to List, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in Python tutorial.
Interview Questions & Answers
append()
method?
Q: What happens if we try to append multiple elements at once using the append()
method only takes a single argument. If we pass multiple elements separated by commas, Python will raise a TypeError
. If we need to append multiple elements, we can either call append()
multiple times or use the extend()
method.
Incorrect use of append()
method => list.append(4, 5)
# This will raise a TypeError
Q: Can we append elements to a list while iterating over it? What are the problems faced?
Yes, we can append elements to a list while iterating over it. If we append elements into the list then list size will keep on changing continuously during the iteration. This change in list size should be handled carefully. If can don’t handle it carefully, it can lead to an infinite loop.
number_list = [1, 2, 3]
for item in number_list:
number_list.append(item + 1)
if len(number_list) > 6:
break
print(number_list) # Final list elements: [1, 2, 3, 2, 3, 4, 3]
In this example, if we don’t use the if
condition len(number_list) > 6
, then this can be an indefinite loop. Final list elements will be [1, 2, 3, 2, 3, 4, 3]
.
append()
method?
Q: What is the time complexity of the In Python, lists are implemented as dynamic arrays and append()
method always elements at end of the list. So, the time complexity of the append()
method is O(1). It means append()
method takes constant amount of time regardless of the size of the list.
Since append()
only adds an element to the end of the list, it doesn’t need to shift elements or reallocate memory unless the list grows beyond its current capacity, which happens infrequently due to the way dynamic arrays are managed.
Q: What happens if we append an element to a list and then modify that element later?
If we append a mutable element (like a list or a dictionary) to another list, and then modify that element later, the change will be reflected in the list because the list stores references to objects, not copies.
number_list = []
sub_list = [1, 2, 3]
number_list.append(sub_list) # number_list refers sub_list object in memory
print(number_list) # number_list will have [[1, 2, 3]]
sub_list.append(4) # append element in sub_list
print(number_list) # new element will also append to number_list [[1, 2, 3, 4]]
After appending sub_list
to number_list
, modifying sub_list
directly affects number_list
because both refer to the same object in memory.
Q: How to append elements of different data types to the same list? Provide an example.
Yes, Python lists are heterogeneous, meaning they can contain elements of different data types.
datatype_list = []
datatype_list.append(23) # Integer
datatype_list.append(43.54) # Float
datatype_list.append("shbytes") # String
datatype_list.append([53, 12, 0]) # List
datatype_list.append(True) # Boolean
print(datatype_list) # Final list: [23, 43.54, 'shbytes', [53, 12, 0], True]
datatype_list
contains different datatype elements. There is an integer, a float, a string, a list, and a boolean element. This shows using append()
method we can add different datatype elements in a list.
Test Your Knowledge: Practice Quiz
Related Topics
- Understanding Lists in Python: A Comprehensive GuideLists in Python List is a core datatype in Python. Lists are sequences used to store elements (collection of data). Lists are similar to Arrays but are of dynamic size. It means the size of the list can be increased or decreased as we add or remove elements from the list. Understanding Python Lists: A…
- How to Create List in Python | Python List Creation Methods ExplainedList is a sequence data type used to store elements (collection of data). Lists are similar to Arrays but have a dynamic size, meaning the list size can increase or decrease as elements are added or removed. A list is a core data type in Python, along with Tuple, Set and Dictionary. Lists in Python…
- How to Access List Elements by Index in Python (with Example Programs)Python list elements are stored based on their index positions and can be accessed by their index positions, which allows to quickly retrieve specific element from the list. Index assignment to list element in Python, is similar to index assigned in Array elements. Understanding how to access list elements by index is crucial for data…
- Python List Index Method Explained with Examples | Get Element Position in ListElements in a Python list are stored based on their index positions. Lists in Python provides an index(arg) method to get the index position of an element within a list. In the previous article How to Access List Elements by Index, we learned how to access a list element using its index position. In this…
- Append Elements to List – Python | Add Elements with Append MethodIn Python, elements in a list can be added using the append(element) method. This method allows us to add elements to the end of a list easily. In the previous articles, we explored accessing list elements by index and using the list index method to retrieve an element’s position. This article covers appending new elements…