To append an element to a list in Python, you can use the .append()
method. Here is an example:
my_list = [1, 2, 3] my_list.append(4) print(my_list) # Output: [1, 2, 3, 4]
In this example, we start with a list [1, 2, 3]
. We then use the .append()
method to add the value 4
to the end of the list. Finally, we print the updated list, which now includes the new value.
You can also use the +
operator to concatenate two lists:
my_list = [1, 2, 3] new_element = [4] my_list = my_list + new_element print(my_list) # Output: [1, 2, 3, 4]
In this example, we first create a new list [4]
and then concatenate it with the original list [1, 2, 3]
using the +
operator. The result is a new list that includes both the original elements and the new element.
insert(index, elmt):
The insert(index, elmt)
method in Python is used to insert an element at a specific index in a list. Here is an example:
my_list = [1, 2, 3] my_list.insert(1, 4) print(my_list) # Output: [1, 4, 2, 3]
In this example, we start with a list [1, 2, 3]
. We then use the .insert()
method to insert the value 4
at index 1
, which moves the original element at index 1
and all subsequent elements one index to the right. Finally, we print the updated list, which now includes the new value.
Note that the first argument to the insert()
method is the index at which to insert the element, and the second argument is the element to insert.
extend(iterable):
The extend(iterable)
method in Python is used to add all the elements of an iterable (such as a list, tuple, or string) to the end of a list. Here is an example:
my_list = [1, 2, 3] my_list.extend([4, 5]) print(my_list) # Output: [1, 2, 3, 4, 5]
In this example, we start with a list [1, 2, 3]
. We then use the .extend()
method to add the values [4, 5]
to the end of the list. Finally, we print the updated list, which now includes all the original values and the new values.
Note that the argument to the extend()
method must be an iterable. In the example above, we passed a list [4, 5]
as the argument, but we could have also used a tuple or a string.