How do I fix a value error: 'CB7' is not in list?

Viewed 36

(Repost for clarity) This function returns the list with the positions of the codes when I put my mouse over the return lst: [1, 4, 7] (as its supposed to) but when I call the function it gives me the error builtins.ValueError: 'CB7' is not in list

I realize that the problem is in [i:].index(single_code) + i

How do I fix it without using enumerate() and list comprehensions?

Here is my code:

sp_codes = ['EB9', 'CB7', 'EB9', 'N4Y', 'CB7', '4B9', '9OP', 'CB7', '4B9']



    return lst
            
    
'''
testing code
'''            
single_code = input('Enter a code: ') #Enter 'CB7'

pos_list = find_indexes(sp_codes, single_code)
print(pos_list) # ---> Prints [1, 4, 7]
1 Answers

This solution should work:

sp_codes = ['EB9', 'CB7', 'EB9', 'N4Y', 'CB7', '4B9', '9OP', 'CB7', '4B9']


def find_indexes(sp_codes, single_code):
    lst = []
    for i in range(0, len(sp_codes)):
        if single_code in sp_codes[i:]:
            index = sp_codes[i:].index(single_code) + i
            if index not in lst:
                lst.append(index)
        else:
            break
    return lst


'''
testing code
'''
single_code = input('Enter a code: ')  # Enter 'CB7'

pos_list = find_indexes(sp_codes, single_code)
print(pos_list)  # ---> Prints [1, 4, 7]

This check weather there is any more occurrences of the code in the list, and if not, breaks out of the loop statement. This prevents it from checking a list without the specified code and so causes no error.

Related