You can use the append() or insert() method to Add the last element in the list in Python. These are two main ways to insert an element at the end of a given list.
list.append(element)
: add the element to the end of the list.list.insert(len(list), element)
: inserts the element before the given index
List Concatenation: We can use the +
operator to concatenate multiple lists and create a new list.
Add the last element in the list Python
Simple example code.
lst = [1, 2, 3]
# append
lst.append(4)
print(lst)
# insert
lst.insert(len(lst), 'Bob')
print(lst)
Output:
extend()
This function adds iterable elements to the list.
extend_list = []
extend_list.extend([1, 2]) # extending list elements
print(extend_list)
extend_list.extend((3, 4)) # extending tuple elements
print(extend_list)
extend_list.extend("ABC") # extending string elements
print(extend_list)
Output:
[1, 2]
[1, 2, 3, 4]
[1, 2, 3, 4, 'A', 'B', 'C']
List Concatenation
If you have to concatenate multiple lists, you can use the +
operator. This will create a new list, and the original lists will remain unchanged.
evens = [2, 4, 6]
odds = [1, 3, 5]
nums = odds + evens
print(nums) # [1, 3, 5, 2, 4, 6]
If you have a list and you want to add an element at a specific index, you can use the insert()
method. For example:
my_list = [1, 2, 3, 4, 5]
# Adding an element at a specific index (e.g., index 2)
new_element = 6
index_to_insert = 2
my_list.insert(index_to_insert, new_element)
print(my_list)
Do comment if you have any doubts or suggestions on this Python list code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.