TypeError: 'list' object cannot be interpreted as an integer

Greysus picture Greysus · Jan 20, 2015 · Viewed 154.7k times · Source

The playSound function is taking a list of integers, and is going to play a sound for every different number. So if one of the numbers in the list is 1, 1 has a designated sound that it will play.

def userNum(iterations):
  myList = []
  for i in range(iterations):
    a = int(input("Enter a number for sound: "))
    myList.append(a)
    return myList
  print(myList)

def playSound(myList):
  for i in range(myList):
    if i == 1:
      winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

I am getting this error:

TypeError: 'list' object cannot be interpreted as an integer

I have tried a few ways to convert the list to integers. I am not too sure what I need to change. I am sure that there is a more efficient way of doing this. Any help would be very greatly appreciated.

Answer

jez picture jez · Jan 20, 2015

Error messages usually mean precisely what they say. So they must be read very carefully. When you do that, you'll see that this one is not actually complaining, as you seem to have assumed, about what sort of object your list contains, but rather about what sort of object it is. It's not saying it wants your list to contain integers (plural)—instead, it seems to want your list to be an integer (singular) rather than a list of anything. And since you can't convert a list into a single integer (at least, not in a way that is meaningful in this context) you shouldn't be trying.

So the question is: why does the interpreter seem to want to interpret your list as an integer? The answer is that you are passing your list as the input argument to range, which expects an integer. Don't do that. Say for i in myList instead.