Search code examples
pythonerror-handlingindex-error

How do you remove numbers greater than or equal to a specified number within a list, in python


So the goal is to take integer inputs, use the first number to tell how many integers are actually on the list, and the last number is the range (so in this case its 100, so everything greater than or equal to 100 on the list should get removed in the print)

Also both the first and last numbers should be removed in the final statement

This is what I could come up with but I encountered two problems: In the first half, it removes everything like its supposed to except the '3000', it seems like its just the element in the list thats not getting removed because, '140' and '100' both get removed like theyre supposed to.

The second problem is in the print statement at the bottom, im not entirely sure why but, its giving "IndexError: list index out of range"

USER INPUT EX.: 5 50 60 140 3000 75 100

numbers = []
integers = int(input())
while True:
    integers = int(input())
    numbers.append(integers)
    firsti = numbers[0]
    if len(numbers) > firsti + 1:     #if the number of items in list (numbers) > the first list item PLUS ONE
        numbers.remove(numbers[0])    #remove the first item
        lastdigi = numbers[-1]
        for number in numbers:    
            if number >= lastdigi:    #removes all numbers >= last digi
                numbers.remove(number) 
        break                         #and prints the rest
    
listnum = len(numbers)                #this whole section is to try and print the numbers from the list
while listnum >= 0:                                                       #and match the example output
    print (numbers[0], end=',')
    numbers.remove(numbers[0])

print(numbers)
#example output: '50,60,75,'
#my output: '50,60,3000,75,'

Solution

  • Here is a solution. The problem is when you used remove() the list lost part of its index.

    
    numbers=[5, 50 ,60, 140 ,3000 ,75, 100]
    #integers = int(input())
    while True:
     #   integers = int(input())
      #  numbers.append(integers)
        firsti = numbers[0]
        if len(numbers) > firsti + 1:     #if the number of items in list (numbers) > the first list item PLUS ONE
            numbers.remove(numbers[0])    #remove the first item
            lastdigi = numbers[-1]
            new_list = []
            for number in numbers:
                if number < lastdigi:    #removes all numbers >= last digi
                    new_list.append(number) # [HERE] you are loosing the index
            break                         #and prints the rest
    
    # this whole section is to try and print the numbers from the list
    for i in new_list:                                                      #and match the example output
        print (i, end=',')
    
    print(new_list)
    
    

    I made some modifications.