Home > Net >  removing numbers form list by python
removing numbers form list by python

Time:01-20

Take 5 integer input from the user.

  1. Remove all numbers less than 9.

  2. Calculate the sum of remaining numbers

        python
        n = int(input("Enter number of elements : "))
        a = list(map(int,input("\nEnter the numbers : "). strip(). split()))
        for i in range(len(a)):
          if a[i]>9:
            a.remove(a[i])
            b=sum(a)
            print(b)
    

CodePudding user response:

When you remove from same list, of course the index will be out of range items from list,

BUT you really don't need to remove those items from list, just don't include them in your sum calculation:

n = int(input("Enter number of elements : "))
a = list(map(int, input("\nEnter the numbers : ").strip().split()))
b = sum([num for num in a if num<= 9])
print(b)
  •  Tags:  
  • Related