[python] Python 'list indices must be integers, not tuple"

I have been banging my head against this for two days now. I am new to python and programming so the other examples of this type of error have not helped me to much. I am reading through the documentation for lists and tuples, but haven't found anything that helps. Any pointer would be much appreciated. Not looking for the answer necessarily, just more resources on where to look. I am using Python 2.7.6. Thanks

measure = raw_input("How would you like to measure the coins? Enter 1 for grams 2 for pounds.  ")

coin_args = [
["pennies", '2.5', '50.0', '.01'] 
["nickles", '5.0', '40.0', '.05']
["dimes", '2.268', '50.0', '.1']
["quarters", '5.67', '40.0', '.25']
]

if measure == 2:
    for coin, coin_weight, rolls, worth in coin_args:
        print "Enter the weight of your %s" % (coin)
        weight = float(raw_input())
        convert2grams = weight * 453.592

        num_coin = convert2grams / (float(coin_weight))
        num_roll = round(num_coin / (float(rolls)))
        amount = round(num_coin * (float(worth)), 2)

        print "You have %d %s, worth $ %d, and will need %d rolls." % (num_coin, coin, amount, num_roll)

else:
    for coin, coin_weight, rolls, worth in coin_args:
        print "Enter the weight of your %s" % (coin)
        weight = float(raw_input())

        num_coin = weight / (float(coin_weight))
        num_roll = round(num_coin / (float(rolls)))
        amount = round(num_coin * (float(worth)), 2)

        print "You have %d %s, worth $ %d, and will need %d rolls." % (num_coin, coin, amount, num_roll)

This is the stack trace:

File ".\coin_estimator_by_weight.py", line 5, in <module>
  ["nickles", '5.0', '40.0', '.05']
TypeError: list indices must be integers, not tuple

This question is related to python list

The answer is


Why does the error mention tuples?

Others have explained that the problem was the missing ,, but the final mystery is why does the error message talk about tuples?

The reason is that your:

["pennies", '2.5', '50.0', '.01'] 
["nickles", '5.0', '40.0', '.05']

can be reduced to:

[][1, 2]

as mentioned by 6502 with the same error.

But then __getitem__, which deals with [] resolution, converts object[1, 2] to a tuple:

class C(object):
    def __getitem__(self, k):
        return k

# Single argument is passed directly.
assert C()[0] == 0

# Multiple indices generate a tuple.
assert C()[0, 1] == (0, 1)

and the implementation of __getitem__ for the list built-in class cannot deal with tuple arguments like that.

More examples of __getitem__ action at: https://stackoverflow.com/a/33086813/895245


To create list of lists, you need to separate them with commas, like this

coin_args = [
    ["pennies", '2.5', '50.0', '.01'],
    ["nickles", '5.0', '40.0', '.05'],
    ["dimes", '2.268', '50.0', '.1'],
    ["quarters", '5.67', '40.0', '.25']
]