Search code examples
pythonpython-2.7appendtypeerrorextend

'append' works but 'extend' fails to work in this case


I was trying to add a value to each of the elements in a list. Here's the code:

c = [1,2,3]
d= []
for i in range(len(c)):
    d.append(c[i]+3)
print (d)

The code just works fine. But if I change it to 'extend' as follows:

c = [1,2,3]
d= []
for i in range(len(c)):
    d.extend(c[i]+3)
print (d)

it would throw a TypeError:

TypeError: 'int' object is not iterable

May I know why is it so?


Solution

  • extend() takes a list as its required parameter. You are giving it an int. Try this:

    c = [1,2,3]
    d= []
    for i in range(len(c)):
        d.extend([c[i]+3])
    print(d)