tumenicooks
tumenicooks

Reputation: 29

Why am I getting Type Error on list += but it works on list.append()

I'm picking up programming on python, am learning how to create basic caesar cypher and ran across the rather common

TypeError: 'int' object is not iterable

I've taken a look around and found out what the type error means but out of curiosity I tried if the code would work with list.append and surprisingly it did. Now I'm puzzled because I thought list.append and list += could be used similarly for adding to a list, below is part of the code that works when using list.append. What's the difference with how these two work or interpreted?

text_to_list = list(text)
list_to_number = []
for letter in text_to_list:
    cipher_num = alphabet.index(letter)
    list_to_number.append(cipher_num)

Upvotes: 1

Views: 51

Answers (1)

linger1109
linger1109

Reputation: 520

The main difference between += and list.append() is that += is used to extend a list by adding values from another list, while append adds a value to the end of the list.

Examples

a = [1, 2, 3]
a.append(3) # now a = [1, 2, 3, 3]

b = [1, 2, 3]
b += [3] # now b = [1, 2, 3, 3]

c = [1, 2, 3]
c += 3 # TypeError

d = [1, 2, 3]
d.append([3]) # now d = [1, 2, 3, [3]]

There is a built in list method, .extend(), which behaves the same as +=.

e = [1, 2, 3]
e.extend([3]) # now e = [1, 2, 3, 3]

f = [1, 2, 3]
f.extend(3) # TypeError

Upvotes: 2

Related Questions