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

+= and list.append() difference

What's the difference between my_list += [6] and my_list.append(6) ?

1 Answer

Hi Daffa

There is a difference, append just adds something to the original list where as += combines the two as its an assignment operator. list.append() is almost alot more efficient in terms of performance. Using the += operator is the same as saying list.extend().

hope this helps.

Seth Kroger
Seth Kroger
56,413 Points

Also to add to that, the difference between append() and extend() is that if you add a list append() will add the whole list as a single item (a list inside a list) while extend will add each element to the target list.

alist = [1, 2, 3, 4]

alist.append([5,6]) # gives you [1, 2, 3, 4, [5, 6]]
   # vs.
alist.extend([5,6]) or alist += [5, 6] # gives you [1, 2, 3, 4, 5, 6]

Thanks for the help!