Hone

Lessons · Python · adding one thing or many

Adding one thing versus adding many

append puts one item on the end; extend opens another list and pours its items in.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Building results is most of programming. Confusing the two gives you a list with a list stuck inside it, and the bug shows up three functions later.

How to think about it

Ask: am I adding one value, or the contents of another collection? One value, even if it is itself a list you want kept whole: append. Contents: extend.

Worked example

basket = ["eggs"]
One item.
basket.append("milk")
Now ["eggs", "milk"]. One thing added.
basket.extend(["tea", "jam"])
Now ["eggs", "milk", "tea", "jam"]. Two things added, individually.
basket.append(["tea", "jam"])
Would give [..., ["tea", "jam"]]: a list inside the list. Usually not what you meant.

Your turn

Add every item from more_items to results, individually.

results = [1, 2]
more_items = [3, 4]
results.(more_items)

The trap

Both return None. results = results.append(x) throws away your list and keeps None.

Practise adding one thing or many on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.