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


Why not to always use .extend? I can add 1 item with that too

With extend I can add not just 2 or more, but one single item. Why not forget append and always use extend?

2 Answers

The (very) short answer is: best practice. They give different results, and have different purposes, so use the best practice--even with only one item.

For example, if you append [4,5] to [1,2,3], you get [1,2,3[4,5]].

But if you extend, you get [1,2,3,4,5]. See the difference? Append "appends" the object "as is"; Extend extends the list and inserts the values.

Nicholas Grenwalt
Nicholas Grenwalt
46,626 Points

They are both very handy tools. Don't knock append until you learn a bit more about it..okay Will. ;) haha Look at these instances I borrowed from a similar StackOverflow question.

letters = ['a', 'b']

letters.extend(['c', 'd']) print(letters) # ['a', 'b', 'c', 'd']

letters.append(['e', 'f']) print(letters) # ['a', 'b', 'c', 'd', ['e', 'f']]

names = ['Foo', 'Bar'] names.append('Baz') print(names) # ['Foo', 'Bar', 'Baz']

names.extend('Moo') print(names) # ['Foo', 'Bar', 'Baz', 'M', 'o', 'o']

Yes, you technically could use extend and make it work. But when you know you only want to add one item but that item might be a list of a bunch of items all neatly put into one spot in a bigger list than append is your go to man. Append makes working with single items a lot easier when things get complex whereas extend can get confusing. To keep things simplistic just remember the general rule of thumb that for single items use append and to apply multiple think extend. It will save a lot valuable energy. haha

I know that wasn't the most thorough answer, but you don't want to dive too deep into that just yet. Keep the learning going Will. :)