Why do I need an iterable?

Why do I keep getting “TypeError: ‘int’ object is not iterable”?
Here’s what I’ve got:

def double_index(lst, index):
if index >= len(lst):
return lst
else:
new_lst = lst[:index] + list(2*lst[index]) + lst[index+1:]
return new_lst

I’m very confused because it seems almost identical to the official solution. What’s wrong with my code and what does this error actually mean?

First, please use the </> icon in the menu bar atop the text box to format your code. Doesn’t this look better?

def double_index(lst, index):
    if index >= len(lst):
        return lst
    else:
        new_lst = lst[:index] + list(2*lst[index]) + lst[index+1:]
    return new_lst

Now, look at this expression:
lst[:index] + list(2*lst[index]) + lst[index+1:]

The second term is list(2*lst[index]), and looking inside of that we see 2*lst[index], which is
2 * list element at index, an int if this is a list of integers.

So that second term is list(some_int), which raises the TypeError,

‘int’ object is not iterable

… since the list() function (actually, type) is designed to take as its parameter an iterable.

1 Like