Show the difference between Python's append() and extend() with both a list and a string.
The difference between the two methods is one single rule. append() adds exactly one new item to the end of the list, no matter what that item is. extend() takes everything inside the argument and adds those items one at a time. That rule explains every result you will ever see.
a = [1, 2]
a.append([3, 4])
print(a) # [1, 2, [3, 4]] - one new element
b = [1, 2]
b.extend([3, 4])
print(b) # [1, 2, 3, 4] - the items are added
c = [1, 2]
c.append('hi')
print(c) # [1, 2, 'hi']
d = [1, 2]
d.extend('hi')
print(d) # [1, 2, 'h', 'i']
The last two lines are the ones that need explaining. extend() accepts any iterable, and a string is an iterable made of single characters, so extending a list with a string adds each letter as its own new element. This surprise catches many beginners. The simple fix is to wrap the string in a list first, so you would write d.extend(['hi']), or you can use append() when you want the whole string to become one item.
The nested list in the first two lines is worth a moment of your attention as well. Appending a list gives you a list inside a list, which is often not what someone means when they write a.append(other_list). When you want a copy of the contents, extend() is the right method. When you want a structure of lists, then a list of lists is correct, but you should say that clearly in your code.
There is also a performance point here. Calling extend() with a list is faster than calling append() inside a loop, because it copies the items in one operation instead of making the list grow again and again. The previous question in this set looked at building lists, and this one explains why the method matters when you add many items at once.