Home > Software engineering >  Python list.remove is not working as expected
Python list.remove is not working as expected

Time:09-29

I have an array of numbers from 0 to 100 and another variable which contains number which user has to guess. If users guess is lower then I am removing every number lower than that. To put it simple I am building binary search algorithm.

Lets say user has to guess number 25. and he wrote 21 as his first guess. if he tried to write 21 again code would crash and give me this error:

ValueError: list.remove(x): x not in list

Here is the code:

import random

    
def binary_search_algo():
    number_to_guess = random.randint(0,100)
    random_number_list = list(range(0,100))
    keep_guessing = True
    print(number_to_guess)
    while(keep_guessing):
        user_guess = int(input('Enter you guess: '))
        if(user_guess < number_to_guess):
            try:
                if(user_guess in random_number_list):
                    print('Too Low')
                    for i in range(user_guess):
                        random_number_list.remove(i 1)
                        print(i)
                else:
                 print('Since your last guess was lower')
                 print('We eliminated every number lower than your previous guess')
                 print('So pick higher number next') 
            except:
                print('Too Low')
        elif user_guess > number_to_guess:
            print('Too High')
        else:
            print('Good job')
            break        


binary_search_algo()    

I tried to fix it by putting it in the try/except and adding 1 to the I but I don't think this is an correct solution. any suggestions please?

CodePudding user response:

ValueError: list.remove(x): x not in list

Put simply this is saying: I can not remove that as it is not present in list. You should check if list does contain given element before requesting its' removal, i.e. in place of

random_number_list.remove(i 1)

do

if (i 1) in random_number_list:
    random_number_list.remove(i 1)

CodePudding user response:

In your current implementation you can use list comprehension to filter out the lower values:

random_number_list = [x for x in random_number_list if x >= user_guess]

Since the list is ordered, the more efficient solution would be to find the position of the actual number in the list, and return just a slice starting at given index.

And even better - you dont need the list random_number_list at all. You need only to remember the highest guessed number below the number_to_guess.

  • Related