Home > Net >  How to write a function to delete a list element in python
How to write a function to delete a list element in python

Time:01-17

I'm learning python and one of the exercises I have to do is to create a deletePerson function that deletes any given person from the list and returns a new list without that persons name.

This is my code so far:

people = ['juan','ana','michelle','daniella','stefany','lucy','barak',"emilio"] 

def deletePerson(person_name):
    new_people = []
    for i in range(0, len(people)):
        if people.index(person_name):
    new_people = people.remove(person_name)
    return new_people

print(deletePerson("daniella"))
print(deletePerson("juan"))
print(deletePerson("emilio"))

So far this code returns "None".

I have also tried this:

people = ['juan','ana','michelle','daniella','stefany','lucy','barak',"emilio"] 

#Your code go here:
def deletePerson(person_name):
    new_people = []
    for i in range(0, len(people)):
        if person_name in people:
    new_people = people.remove(person_name)
    return new_people

print(deletePerson("daniella"))
print(deletePerson("juan"))
print(deletePerson("emilio"))

Also returns "None"

I know my code might be completely wrong, but its what I got so far.

I tried using index() to find person_name and then remove() to then append the result to new_people.

Also tried: if person_name in people:

What I want is that when I call the function and I pass it a persons name, it removes it from the list and return the new list without the removed name.

CodePudding user response:

A fixed version of your code. This will always return your people list with the name deleted if the name is found in the list.

people = ['juan','ana','michelle','daniella','stefany','lucy','barak',"emilio"] 

def deletePerson(person_name):
    if person_name in people:
        people.remove(person_name)
    return people

print(deletePerson("daniella"))
print(deletePerson("juan"))
print(deletePerson("emilio"))

print(people)

Output:

['juan', 'ana', 'michelle', 'stefany', 'lucy', 'barak', 'emilio']
['ana', 'michelle', 'stefany', 'lucy', 'barak', 'emilio']
['ana', 'michelle', 'stefany', 'lucy', 'barak']
['ana', 'michelle', 'stefany', 'lucy', 'barak']

If you don't want to remove name from the original list which is people, you can copy it before applying remove
Example:

def deletePerson(person_name):
    new_list = people.copy()
    if person_name in new_list:
        new_list.remove(person_name)
    return new_list


print("This is new list") 
print(deletePerson("daniella"))

print("This is original list") 
print(people) 

Output:

This is new list
['juan', 'ana', 'michelle', 'stefany', 'lucy', 'barak', 'emilio']

This is original list
['juan', 'ana', 'michelle', 'daniella', 'stefany', 'lucy', 'barak', 'emilio']
  • Related