Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Eliminate list inside an array if it contains input

I recently started learning python and working with arrays. I need to check if inside my array an inputted code exists abd if it does delete the whole list that contains it. My code is the following:

room = 'F22'
array = [['F22', 'Single', 'Cash']]

def deleteReservation(room, array):
    print(array)
    for x in array:
        for i in x:
            if room in i:
                index = array.index(room)
                mode = validateNum(0, '1 To confirm, 2 to cancel.: ', 3)
                if mode == 1:
                    array = array.pop(index)
                    return array
                elif mode == 2:
                    return 'Canceled.'
        else:
            return "Reservation was not found."

But I keep getting the following mistake:

Traceback (most recent call last):
index = array.index(room)
ValueError: 'F22' is not in list

My guess is that the error is inside the nested loop, but I can’t find it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this


room = 'F22'
array = [['F22', 'Single', 'Cash']]

def deleteReservation(room, array):
    print(array)
    for x in array:
        if room in x:
            index = x.index(room)
            mode = validateNum(0, '1 To confirm, 2 to cancel.: ', 3)
            if mode == 1:
                array = array.pop(index)
                return array
            elif mode == 2:
                return 'Canceled.'
        else:
            return "Reservation was not found."

Why did You get this error?

Error in this line

array.index(room) # here array is for full list `[['F22', 'Single' 'Cash']]`, and you try to get the index of `F22`from this,

# as you loop through the array

for x in array:
    print(x) # here you get x = `['F22', 'Single' 'Cash']` this is the list from inside the array list, Hence you can use x.index('F22') 'cause `F22` present in x. not in array (array only has one element which is `['F22', 'Single' 'Cash']`.)



Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading