-1

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?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Dennis
  • 175
  • 1
  • 3
  • 8

1 Answers1

1

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)
dustintheglass
  • 197
  • 1
  • 11