How to write function that take a list and number X .If X exist in list in index ‘m’, it should return sum of elements of list from index ‘m’

Issue

def func(x):
    lst=list(map(int,input("Enter a list of numbers: ").split()))
    flag=0
    num=0
    for i in lst:
         if x==i:
                flag=1
                
    if flag==1:
        ab=lst.index(x)
        for i in range(ab,len(lst),1):
            num=lst.index(ab)
            num=num+lst[i]
            print(num)
    return num
        
    
y=input("Enter a number present in the list: ")
print(func(y)) 

Above is the function to find all numbers and sum from index m. It takes a number from the user,gets the index and prints the sum of the number from index m. But the code output is 0 in this case

Solution

First of all, you can use split() with empty parameter.

And a solution of your problem is:

    def func(x):
    a=input("Enter list of Numbers: ")
    lst=list()
    for i in a:
        try:
            i=int(i)
            lst.append(i)
        except:
            pass
    num=0
    x=int(x)
    for i in (lst):
        if x==i:
            index=lst.index(x)
            for i in range(index,len(lst),1):
                num=num+lst[i]
    return num
        
        
    
y=input("Enter a number present in the list: ")
print(func(y)) 

instead of map i have used the for loop to covert the string to a integer list.
then if x==i i searched the index of x in the list and from the index i start to sum the numbers again using a for loop.

Answered By – Faraaz Kurawle

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.