⊗pyPmLsEGR 52 of 208 menu

Getting and Removing an Element from a List in Python

If we need to remove an element, but still display its value, we use the pop method. We pass the index of the element we need to its parameter:

lst = [1, 2, 3] print(lst.pop(0)) # 1

You can also use the pop method to remove the last element from the list. To do this, we simply leave the method parameter empty:

lst = [1, 2, 3] print(lst.pop()) # 3 print(lst) # [1, 2]

Given a list:

lst = ['a', 'b', 'c', 'd', 'e']

Get the last element into a variable, removing it in the process.

Given a list:

lst = ['a', 'b', 'c', 'd', 'e']

Get the first element into a variable, removing it in the process.

Given a list:

lst = ['a', 'b', 'c', 'd', 'e']

Get the second element into a variable, removing it in the process.

byenru