What if I use += instead of append?

Help to understand please.
If i use list concantinashion (+=), not .append we get:

highlighted_poems_list = ['Afterimages:Audre Lorde:1997', '  The Shadow:William Carlos Williams:1915']

highlighted_poems_stripped = []
for item in highlighted_poems_list:
    highlighted_poems_stripped += item .strip()

print(highlighted_poems_stripped)

[‘A’, ‘f’, ‘t’, ‘e’, ‘r’, ‘i’, ‘m’, ‘a’, ‘g’, ‘e’, ‘s’, ‘:’, ‘A’, ‘u’, ‘d’, ‘r’, ‘e’, ’ ', ‘L’, ‘o’, ‘r’, ‘d’, ‘e’, ‘:’, ‘1’, ‘9’, ‘9’, ‘7’, ‘T’, ‘h’, ‘e’, ’ ', ‘S’, ‘h’, ‘a’, ‘d’, ‘o’, ‘w’, ‘:’, ‘W’, ‘i’, ‘l’, ‘l’, ‘i’, ‘a’, ‘m’, ’ ', ‘C’, ‘a’, ‘r’, ‘l’, ‘o’, ‘s’, ’ ', ‘W’, ‘i’, ‘l’, ‘l’, ‘i’, ‘a’, ‘m’, ‘s’, ‘:’, ‘1’, ‘9’, ‘1’, ‘5’]

But, item[0] in is not a single letter, item [0] is Afterimages:Audre Lorde:1997.

print(highlighted_poems_list[0])

Afterimages:Audre Lorde:1997

OR:

for item in highlighted_poems_list:
    print(item)

Afterimages:Audre Lorde:1997
The Shadow:William Carlos Williams:1915

So, if i use .append oll is good:

highlighted_poems_list = ['Afterimages:Audre Lorde:1997', '  The Shadow:William Carlos Williams:1915']

highlighted_poems_stripped = []
for i in highlighted_poems_list:
    highlighted_poems_stripped.append(i.strip())

print(highlighted_poems_stripped)

[‘Afterimages:Audre Lorde:1997’, ‘The Shadow:William Carlos Williams:1915’]

Why in for loop we must use .append?

The += operator wants both of its operands to be of the same type, so if you say
my_list += my_string, it first does list(my_string), and then works like list.extend().

6 Likes

It should be noted this only applies to string lists, not number lists.

>>> a = ['a', 'b', 'c', 'd']
>>> a += 'e'
>>> a
['a', 'b', 'c', 'd', 'e']
>>> b = [1,2,3,4]
>>> b += 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> 
3 Likes

Yes, thanks; the right-hand object must be iterable, as with extend().

3 Likes

So,

>>> b += [5]
b += [5]
>>> b
[1, 2, 3, 4, 5]
>>> 
3 Likes

Why is int not iterable?

Because an int is a singular, exact value.

b = [1,2,3,4]
b += [5]
print (b)    # [1, 2, 3, 4, 5]

Above we concatenated two list objects.

b.append(6)
print (b)    # [1, 2, 3, 4, 5, 6]