Home > Mobile >  How do I use list comprehension with an if-else statement to print if the action has been completed
How do I use list comprehension with an if-else statement to print if the action has been completed

Time:01-06

So I have a code which asks to find the name of the driver and if it exists to delete that list from the main driver details list. I used a nested list to achieve this. And after deleting the list, I want a message to be displayed saying "Record Deleted" or else "Record Not found".

driver_details=[["Ken Block","55","Hoonigan","Mustang"], ["Ken Miles","48","Ford","Ford GT"]]

def delete_driver():
    """This function is used to delete driver details
    by entering the driver name"""
    global driver_details
    driver_name=input("Enter driver name: ")
    if driver_name in driver_details:
        driver_details=[x for x in driver_details if x[0] not in driver_name]
        print("Driver details deleted")
    else:
        print("Record Not Found")
    print(driver_details)
    options()

This doesn't seem to work for me.

However when I try this:

    """This function is used to delete driver details
    by entering the driver name"""
    global driver_details
    driver_name=input("Enter driver name: ")
    driver_details=[x for x in driver_details if x[0] not in driver_name ]
    print("Driver details deleted")
    print(driver_details)
    options()

It does delete the record.

I expected the answer to print as Record Deleted yet I keep getting Record not found even though the name of the driver does exist. How could I add an if statement to this?

CodePudding user response:

Your code works perfectly fine for me. However, there are 2 corrections:

1.You have to flatten the nested dictionary driver_details to check in property

  1. There is a typo driver_name in drivers_details should be driver_name in driver_details.

driver_details=[["Ken Block","55","Hoonigan","Mustang"], ["Ken Miles","48","Ford","Ford GT"]]

def delete_driver():
    """This function is used to delete driver details
    by entering the driver name"""
    global driver_details
    driver_name=input("Enter driver name: ")
    if driver_name in [item for sublist in driver_details for item in sublist]:  #flattened nested list
        driver_details=[x for x in driver_details if x[0] not in driver_name]
        print("Driver details deleted")
    else:
        print("Record Not Found")
    print(driver_details)

CodePudding user response:

This is how to delete from driver_details:

driver_details2 = [dd for dd in driver_details if dd[0] != driver_name]
driver_details[:] = driver_details2  # Overwrite original list.

There are some other problems with your code (as it is posted), for example the drivers_list variable is not defined. You can define it like this:

drivers_list = [dd[0] for dd in driver_details]
  • Related