Home > Enterprise >  Eliminate list inside an array if it contains input
Eliminate list inside an array if it contains input

Time:05-20

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.

CodePudding user response:

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']`.)



CodePudding user response:

You should index your main array with the whole array where the room from. May be try this

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

def deleteReservation(room, array):
    print(array)
    for index,x in  enumerate(array):
        for i in x:
            if room == i:
                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."

deleteReservation(room,array)
  • Related