Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply all elements of a list together (another list index out of range issue)

In a program I'm writing, I need to multiply each element of a list with all the other elements, like this:

List = [i1, i2, i3]

Result = [i1*i2, i1*i3, i2*i3]

I've been messing around with loops for a while now, but I can't seem to get it to work. This is what I have so far (doesn't work, I know why it doesn't work, just asking for advice):

def function():
    for j in range(len(list)):
        n = j+1
        for i in range(len(list)):

            if n+i > len(list):
                n -= 1
            x = factor[j] * factor[j+i]

            result.append(x)
    return
like image 556
Marek Hríbik Avatar asked Jan 01 '17 19:01

Marek Hríbik


People also ask

How do I fix list index out of range?

The Python IndexError: list index out of range can be fixed by making sure any elements accessed in a list are within the index range of the list. This can be done by using the range() function along with the len() function.

How to avoid index out of range error?

This index error is triggered when indexing a list using a value outside of its range of indexes. The best way to avoid it is by carefully considering what range of indexes a list might have, taking into account that list indexes start at zero instead of one.

How can I multiply all items in a list together with Python?

We can use numpy. prod() from import numpy to get the multiplication of all the numbers in the list. It returns an integer or a float value depending on the multiplication result.

Why is my index out of range Python?

The error “list index out of range” arises if you access invalid indices in your Python list. For example, if you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an IndexError telling you that the list index is out of range.


3 Answers

from itertools import combinations

xs = [1, 2, 3]
products = [x1 * x2 for x1, x2 in combinations(xs, 2)]
like image 146
FMc Avatar answered Oct 21 '22 20:10

FMc


input_list = [1, 2, 3, 4]
result_list = []

for i in range(len(input_list)):
    for j in range(i + 1, len(input_list)):
        result_list.append(input_list[i] * input_list[j])

print(result_list)

Result:

[2, 3, 4, 6, 8, 12]
like image 29
ADR Avatar answered Oct 21 '22 20:10

ADR


As FMc says, itertools is the simplest solution. However, it might be helpful to look at what's wrong with the code you gave, instead of just writing completely new code. There are three issues:
1. You use two different names for your list (list and factor).
2. You include products of the form factor[j]*factor[j] when i is 0.
3. What you do when i+n is out of range doesn't work -- it could still result in something out of range.
A possible solution to 3 is to simply break out of the inner loop at this point: if you're out of range, you don't want to do anything for this i or for larger i with the same j. So that would give

for j in range(len(factor)):
    n = j+1
    for i in range(len(factor)):
        # we are now going to look up factor[n+i] so need >=
        if n+i >= len(factor): 
            break
        # to ensure the second factor is later, use [n+i]>=j+1
        x = factor[j] * factor[n+i]
        result.append(x)

However, a better method to loop through the list like this is to use enumerate:

for j,x in enumerate(factor):
    # x is a list element, j is its index
    for y in factor[j+1:]:
        # loop through remaining elements by slicing
        result.append(x*y)
like image 30
Especially Lime Avatar answered Oct 21 '22 21:10

Especially Lime