-2

I am trying to add the third element of every sub list together in my 2 dimensional list. I have tried this.

total_order = [['Steve', 45, 6],['Miranda', 56, 3],['Alice', 34, 8]]
total_cost = 0
for i in total_order:
    total_cost += total_order[i][2]
    i += 1

I am receiving this error:

TypeError: list indices must be integers or slices, not list

5 Answers 5

2

looping over a list of lists does not give you the index of a list, but the actual list itself.

I renamed your i to order

total_order = [['Steve', 45, 6], ['Miranda', 56, 3], ['Alice', 34, 8]]
total_cost = 0
for order in total_order:
    total_cost += order[2]

but I'd suggest you look into "Generator Expressions" and use the builtin sum function:

total_order = [['Steve', 45, 6], ['Miranda', 56, 3], ['Alice', 34, 8]]
total_cost = sum(order[2] for order in total_order)
2

Problem is that in your case is not number but a list. Put print(i) there and you will see.

['Steve', 45, 6]
['Miranda', 56, 3]
['Alice', 34, 8]

You should have:

total_cost += i[2]
1

total_order is a list of lists, when you iterate over that object the way you did, you're getting a list object - hence the error. You can iterate it using enumerate or a simpler method:

total_cost = sum([item[2] for item in total_order])

Output would be:

17

if you're not into list comprehensions then:

for i in range(len(total_order)):
    total_cost += total_order[i][2]

will output the same.

1
  • thank you very much I did not realise it was this simple. it makes sense now :)
    – user4444
    Jun 24, 2020 at 11:00
1

You can try to add the second item of i

total_order = [['Steve', 45, 6],['Miranda', 56, 3],['Alice', 34, 8]]
total_cost = 0
for i in total_order:
    total_cost += i[2]
print(total_cost)

OR to use enumarte to iterate by index

for i, _ in enumerate(total_order):
    total_cost += total_order[i][2]

Output

17
0

Use the index method of Python lists:

total_order = [['Steve', 45, 6],
               ['Miranda', 56, 3],
               ['Alice', 34, 8]
               ]
total_cost = 0

for i in total_order:
    total_cost += total_order[total_order.index(i)][2]

print(total_cost)

Giving:

17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.