Scripting

Python List pop() Method

Python List pop() Method

Introduction

The pop() list is a built-in Python method that deletes an element by a specified position. It will print out a new list without the deleted elements. If you don’t specify the position, it will remove the last element. If you specify a position out of range, it will return IndexError.

Now we’re gonna teach you to use the pop() method in Python.

Example

list = [1, 2, 3, 4]

list.pop(1)

print(list)

Output:

[1, 3, 4]

Definition

The list pop() method will remove the element at the position you want to remove.

If you don’t specify the position, it will remove the last element.

The syntax

list.pop(pos)

Parameter Values:

pos: the position you want to remove

More examples

Example 1: Remove the last element

list = [1, 2, 3, 4]

list.pop()

print(list)

Output:

[1, 2, 3]

Example 2: Remove the first element

list = [1, 2, 3, 4]

#I remove the 1st element

list.pop(0)

print(list)

Output:

[2, 3, 4]

Example 3: IndexError

list = [1, 2, 3, 4]

list.pop(5)

print(list)

Output:

IndexError: pop index out of range

Conclusion

We just taught you to use the pop() method in Python.

Thank you for referring!

Similar Posts