Search code examples
pythonpython-2.7for-loopenumerate

enumerate(list) removes items from a list and convert it to string/int


This question is just out of curiosity. Suppose I have the list x

   x = ['a', 'b', 'c', 'd', 'e']

When I enumerate through this list and make an intended mistake as follow:

  for i, x in enumerate(x):
      print i + " : " + x 
      #Should use str(i) and str(x)

predictably this error is produced:

    Traceback (most recent call last):
      File "<pyshell#26>", line 2, in <module>
        print i + " : " + x
    TypeError: unsupported operand type(s) for +: 'int' and 'str'

However x list is converted to one letter string 'a'.

  print x
  'a'

I tried the same with numerical list x = [1, 2, 3, 4] and x was converted to and integer of 1.

Why did this happen? and why it did not happen when I use str(i) and str(x)?


Solution

  • The issue with enumerate here is a distraction. The real issue is that you have a list called x and then you assign the values within the list to the name x in your for loop.

    The code doesn't actually crash until you get to:

    print i + " : " + x 
    

    Well, by then, the re-binding of the name has already occurred on the previous line:

    for i, x in enumerate(x):
    

    Now x points to a different object - the first item in your list, regardless of whether that's a string or an integer. Rename either your list or the loop variable.