How to add an element to a list in Python?
Published on Aug. 22, 2023, 12:17 p.m.
To add an element to a list in Python, you can use the append()
method, which adds the element to the end of the list. Here’s an example:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
Output:
[1, 2, 3, 4]
In this example, we define a list of numbers and then use the append()
method to add the number 4 to the end of the list. The resulting list is [1, 2, 3, 4]
.
If you want to add multiple elements to a list, you can use the extend()
method, which takes an iterable as an argument and adds each element from the iterable to the end of the list. Here’s an example:
my_list = [1, 2, 3]
other_list = [4, 5, 6]
my_list.extend(other_list)
print(my_list)
Output:
[1, 2, 3, 4, 5, 6]
In this example, we define two lists and then use the extend()
method to add each element from other_list
to the end of my_list
. The resulting list is [1, 2, 3, 4, 5, 6]
.