Removing Elements from an Array

Another command that makes working with arrays easier is the pop() command, which removes the element at the index specified in the parentheses from the array and returns its value. Similar to the append() command, it uses dot notation.

Let's look at an example:

colors = ["Blue", "Green", "Pink"]
thirdColor = colors.pop(2)
print(thirdColor) # Prints: Pink
print(colors) # Prints: ['Blue', 'Green']

The command colors.pop(2) removed the element at index 2 from the array colors. The value of this element ("Pink") was stored in the variable thirdColor. Then we printed the variable thirdColor and the array colors.

If no index is specified in the parentheses, the last element of the array is removed:

grades = [1, 1, 1, 2]
lastGrade = grades.pop()
print(lastGrade) # Prints: 2

Instructions

Remove the last colleague from the colleagues array using the pop() command and store it in a variable named lastColleague.

Print the value of the variable lastColleague.

Print the value of the variable colleagues.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

7/10

Removing Elements from an Array | Start Coder