Python List Methods

These are like little tools that help us manipulate our lists with ease. And by “ease,” I mean without having to write a bunch of code ourselves.
First up, we have the append() method. This one is pretty straightforward it adds an element to the end of your list. For example:

# Create a list with three elements
my_list = [1, 2, 3]

# Use the append() method to add a new element to the end of the list
my_list.append(4) # Adds a 4 to the end of our list

# Print the updated list
print(my_list) # Output: [1, 2, 3, 4]

Now removing elements from your list using the remove() method. This one is also pretty simple it removes the first occurrence of a given element in your list. But what happens if that element isn’t there? Well, Python will throw an error and you’ll have to handle it yourself (more on that later). For example:

# Create a list with three elements
my_list = [1, 2, 3]

# Remove the element 2 from the list using the remove() method
my_list.remove(2) # Removes the first occurrence of a 2 in our list

# Print the updated list
print(my_list) # Output: [1, 3]

# The remove() method removes the first occurrence of a given element in the list.
# If the element is not present in the list, it will throw an error.
# In this case, the element 2 is removed from the list and the updated list is printed.

But what if we want to remove an element that isn’t there? Let’s say we have this list:

# Create a list with three elements
my_list = [1, 2, 3]

# Try to remove an element that doesn't exist in the list
# This will result in an error, so we need to handle it
try:
    my_list.remove(5) # Removes the first occurrence of a 5 in our list (which doesn't exist)
except ValueError:
    print("Element does not exist in the list")

# Print the updated list
print(my_list)

# Output: [1, 2, 3]

In this case, Python will throw an error and you’ll have to handle it yourself using try-except statements or by checking if the element is present before removing it. But that’s for another tutorial! For now, let’s focus on some of the other list methods in Python.

Stay tuned for more coffee talk about lists next time!

SICORPS