Python List - Pop Method

Method Name:

pop

Method Signature:

pop([index_in])

Method Overview:

  • The pop() method removes an element from the list as specified by the index_in parameter.
  • If, no index is specified the last element in the list is removed.

Parameters:

index_in: Index of the element that is to be removed from the list. The parameter is optional. The square brackets in the method signature denotes that the parameter is an optional one.The last element of the list is removed if this parameter is not specified while calling.

Return Value:

The removed element is returned by the pop() method.

Example 1 - Pop a list element using an index:

# Example Python program that pops an item from a list using an index

# Create a Python list
fruits = ["Apple", "Orange", "Pineapple", "Water Melon",];

# Remove the first item from the list
removed = fruits.pop(0);
print("---Removed---");
print(removed);

# Again remove the first item from the modified list
removed = fruits.pop(0);
print(removed);

# Remove the second item from the modified list
removed = fruits.pop(1);
print(removed);

print("---Remaining---");
for fruit in fruits:
    print(fruit);

Output:

---Removed---
Apple
Orange
Water Melon
---Remaining---
Pineapple

Example - Pop a list element without using an index:

# Example Python program that pops the last item from a list without using an index

# Create a list
colorList = ["Red", "Orange", "Yellow",
             "Green", "Blue", "Indigo",
             "Violet"];

# Remove the last item from the list
removedColor = colorList.pop();

print("---Removed Color:---");
print(removedColor);

print("---Remaining colors in the list:---");
for color in colorList:
    print(color);

Output:

---Removed Color:---
Violet
---Remaining colors in the list:---
Red
Orange
Yellow
Green
Blue
Indigo

 


Copyright 2023 © pythontic.com