You are on page 1of 3

In Python, the pop() method is used to remove and return an element from a list.

It can be
called with or without an index as an argument, and its behavior depends on how it's used:
Without an index:
When called without an index (e.g., my_list.pop()), it removes and returns the last element from
the list. This is often used when you want to remove and process the last item in the list.
With an index:
When called with an index (e.g., my_list.pop(index)), it removes and returns the element at the
specified index. This allows you to remove and access an element from a specific position in the
list.
Here's an example:

Keep in mind that if you try to pop() from an empty list or use an index that is out of bounds
(e.g., an index larger than the list's length), it will raise an IndexError. So, it's a good practice to
check the length of the list or handle potential errors when using pop().
In Python, the insert() method is used to insert an element at a specified index in a list. The
general syntax for the insert() method is:

index: The index at which you want to insert the element. It represents the position in the list
where you want to add the new element.
element: The element you want to insert into the list.
Here's an example of how to use the insert() method:

In this example, the insert(2, 6) call inserts the value 6 at index 2, pushing the elements at and
after index 2 one position to the right.
It's important to note that if you specify an index that is greater than the current length of the
list, the element will be inserted at the end of the list. If you specify a negative index, it counts
from the end of the list, with -1 being the last element.
In Python, the append() method is used to add an element to the end of a list. It is a commonly
used method for extending the list by adding a single element. The general syntax for the
append() method is:

element: The element you want to add to the end of the list.
Here's an example of how to use the append() method:

In this example, the append(4) call adds the value 4 to the end of the my_list.
The append() method is efficient for adding elements to the end of a list because it has a time
complexity of O(1), meaning it takes constant time to perform regardless of the list's size.
It's important to note that append() adds the entire element as a single item to the end of the
list. If you want to add multiple elements from another iterable (e.g., another list) to your list,
you can use the extend() method or the + operator.

You might also like