0

I am completely new to Python and I have an error I don't understand. I have a function called mult1 which I want to take a list "a" and multiply each element together and output the total so that a list of [1,2,3,4] would output 24. I am getting an error "list index is out of bounds" at line 4

def mult1(a):
   n=1
   for i in a:
      n=n*a[i-1]
   print(n)

My function works with the input [1,2,3,4] but not with [7,8,1,2]. Why is this?

Porteous96
  • 97
  • 2
  • 11

4 Answers4

1

you are actually iterating over the values and not the indices. hence i refers to the value in the list

def mult1(a):
   n=1
   for i in a:
      n=n*i
   print(n)
AbtPst
  • 7,778
  • 17
  • 91
  • 172
-1

My function works with the input [1,2,3,4] but not with [7,8,1,2]. Why is this

When you read the first number 7, then 7 is assigned to i. Then you try to lookup the number at a[i-1] => a[7-1] =>a[6]--and 6 is out of bounds.

You don't need to get the index of the numbers in the list to multiply all the numbers together:

def mult1(nums):
    total = 1

    for num in nums:
        total *= num

    print(total)

mult1([7,8, 1, 2])

--output:-
112
7stud
  • 46,922
  • 14
  • 101
  • 127
-1

the python for loop relies on the iteration protocol so when you write

for i in a:
  print(a)

you are actually accessing those indices hence there's no need to use the [i] (indexing ) notation like you would do in a conventional c/c++/java for-loop.

to answer your question

def mult1(a):
  n = 1
  for i in a:
    n *= i
  return n
Ishan Khare
  • 1,745
  • 4
  • 28
  • 59
-2

I will start with explaining the behavior you have observed, and finish by showing a much better way of achieving your goal.

When you use [1, 2, 3, 4] the for loop evaluates to n=n*a[0], n=n*a[1], n=n*a[2] and n=n*a[3] and that works as you have 4 elements in the list.

However, when your list is [7, 8, 1, 2] the first iteration of the for loop evaluates to n=n*a[6] which throws an Index out of bounds exception has it tries to access the 7th element of a 4 element list.

There are many simple ways to multiply all the elements in a list. Two of them:

print (functools.reduce(lambda x,y: x*y, [7, 8, 1, 2]))
>> 112

####################

li = [7, 8, 1, 2]
mul = 1
for num in li:
    mul *= num
print (mul)
>> 112
DeepSpace
  • 78,697
  • 11
  • 109
  • 154