educative.io

Educative

Solution Review: List of Products of All Elements

    def find_product(lst):
    result = []
    left = 1  # To store product of all previous values from currentIndex
    for i in range(len(lst)):
        currentproduct = 1  # To store current product for index i
        # compute product of values to the right of i index of list
        for ele in lst[i+1:]:
            currentproduct = currentproduct * ele
        # currentproduct * product of all values to the left of i index
        result.append(currentproduct * left)
        # Updating `left`
        left = left * lst[i]

    return result

Can you explain how come the line for ele in lst[i+1:]: did not go out of index during the last iteration of the our for loop?


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

@Sodiq_Afolayan
In for ele in lst[i+1:]: , lst [i+1] is used to calculate the product of all the numbers to the right of the current element. If we remove +1 and only write lst [i] then it will not calculate the product of all numbers to the right. It will only take the product of all the elements with each other and gives the wrong output. For reference, I have attached the screenshot for the case if we write i instead of i+1.


Thank you :blush: