Home > Blockchain >  index of element of nested list, try and except
index of element of nested list, try and except

Time:09-30

Have just started programming and are now stuck on a problem. Want to find the index of a number that a user enters in a nested list. If it is not a number or if the number is not in the list, the program should continue running until a valid number is written. Then it should return a tuple with the index. The ONLY parameter to the function is a list of strings. My code, which generates an infinite loop.... Appreciate all the help

def find(mylist):

    for sub_list in mylist:

        while True:    

            try:
                num in sub_list
                num = int(input("Enter a number: "))
                
                
            
            except:
                print(f"{num} is not in the list")
                continue
            else:
                break
        return (mylist.index(sub_list), sub_list.index(num))

row, col = find([['23', '24', '25'], ['26', '27', '28'], ['29', '30']])
print(row, col)

## num is 24,  should print 0,1
## num is 44, 44 is not in the list. Enter a number

CodePudding user response:

Separate the task of finding the number from your input loop. For example, have find simply look for a single value and raise if it's not found -- then call find in your loop with a try/except.

def find(mylist, val):
    for i, sub_list in enumerate(mylist):
        if val in sub_list:
            return i, sub_list.index(val)
    raise ValueError(f"{val} is not in the list.")


while True:
    try:
        print(find(
            [['23', '24', '25'], ['26', '27', '28'], ['29', '30']],
            input("Enter a number: ")
        ))
        break
    except ValueError as e:
        print(e)
Enter a number: 44
44 is not in the list.
Enter a number: 24
(0, 1)

CodePudding user response:

If i need this to be in one function and only with one parameter (list) somewhat like

def find(mylist):
    num =input("Enter num: ")
    for i, sub_list in enumerate(mylist):
        if num in sub_list:
            return i, sub_list.index(num)
   raise ValueError(f"{num} is not in the list.")

# Also the error handling within the fuction

    while True:
        try:
            find(mylist)
            break
        except ValueError as e:
            print(e)

How can we make this work?

row, col = find([['23', '24', '25'], ['26', '27', '28'], ['29', '30']])
print(row,",",col)

## Enter num: 24
0 , 1
  • Related