Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

.append in python

I'm confused about the interchangability of .append and +=. Each one gives me a different output but I do not understand why. When I did the morsecode challenge in OO-Python, for += I kept getting an error, but for .append, it passed. Can anyone explain please.

1 Answer

In the context of lists, += concatenates 2 lists together, but .append adds an object to the end of a list. Here's an example:

>>> numbers = [1, 2, 3]
>>> numbers += 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>> numbers += [4, 5, 6]
>>> print(numbers)
[1, 2, 3, 4, 5, 6]
>>> numbers.append(7)
>>> print(numbers)
[1, 2, 3, 4, 5, 6, 7]
>>> numbers.append([8, 9, 10])
>>> print(numbers)
[1, 2, 3, 4, 5, 6, 7, [8, 9, 10]]

In other words, when you use += with a list, it adds the contents of the 2nd list onto the end of the first so everything is in the same list. If you try to += a list with anything other than a list, it'll throw a TypeError because it needs to take a list. Using .append takes whatever you give it and puts it in the last index of the list. If you give it a number, it'll go on the end of the list without raising an error (as will any other data type). If you give it a list, that whole list will be placed inside the first list

Thank you so much Michael. This was a big help!