Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a Python array element by name

In a Python array, I need to know (if possible) how to delete an array element by its name, without knowing the index of the element in the array.

So, if I had this array defined

usernames = ["Billy", "Bob", "Apple"]

Then we would have three array elements.
Billy, Bob, and Apple.
And then if I had this code

# Deleting the element
def delete_username():
    to_delete = raw_input("Username to remove:")
    # (Code to delete by element name)

I need to know how to delete the element in the array by it's name.
For example, if the user entered "Billy," and the program didn't know the index of Billy in the array, how would we delete Billy from the array, just knowing its name?

like image 601
MysteryBlokHed Avatar asked Aug 04 '26 10:08

MysteryBlokHed


1 Answers

You can also use remove

usernames = ["Billy", "Bob", "Apple"]
if "Billy" in usernames:
    usernames.remove("Billy")
# usernames = ["Bob", "Apple"]
like image 79
Greg Avatar answered Aug 05 '26 23:08

Greg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!