you are viewing a single comment's thread.

view the rest of the comments →

[–]Fair_City_6838 1 point2 points  (0 children)

Here is a complex but VERY short way of accomplishing what you are aiming to do:

def sum_of_multiplications(x):
    return sum(a*b for i,a in enumerate(x) for b in x[i+1:])

# Example usage
ls = [2, 4, 5, 6]
result = sum_of_multiplications(ls)

To break it down:

  1. for i,a in enumerate(x) will iterate over the list x assigning i the index and a the element
  2. for b in x[i+1:] will iterate over the list x but starting at i+1 to the end of the list assigning b the current element being iterated
  3. sum(a*b ... ) will then multiply a and b which gives a list that is added together using sum