Python Introducing Lists Meet Lists Addition

Perfect Storm
Perfect Storm
1,036 Points

What's the difference between append and extend in this example?

I don't understand what differentiates append and extend. Is it that append is for one item as a string and extend is for adding multiple items?

🍹 Dave 🌴 StSomeWhere
🍹 Dave 🌴 StSomeWhere
17,003 Points

It is possible that if you try experimenting in your REPL you might get a better understanding of the difference between the two methods.

Something like below could be a good start:

list1 = ['a', 'b', 'c']
list2 = ['d','e', 'f']
list3 = [1, 2, 3]
str1 = "String Example"
dict1 = {'name':'dict one', 'type':'sample'}
dict2 = {'name':'dict two', 'type':'another sample'}
list1.append(list2)
list1
['a', 'b', 'c', ['d', 'e', 'f']]
list1.extend(list3)
list1
['a', 'b', 'c', ['d', 'e', 'f'], 1, 2, 3]
list1.extend(dict1)
list1
['a', 'b', 'c', ['d', 'e', 'f'], 1, 2, 3, 'name', 'type']
list1.append(dict2)
list1
['a', 'b', 'c', ['d', 'e', 'f'], 1, 2, 3, 'name', 'type', {'name': 'dict two', 'type': 'another sample'}]

1 Answer

Steven Parker
Steven Parker
148,790 Points

The "append" method adds a single item to a list, though the item might be another list. On the other hand, "extend" will add another list as individual items. You can see this in the example you provided:

list1.append(list2)
list1
['a', 'b', 'c', ['d', 'e', 'f']]           # list2 is still a list, INSIDE the big list
list1.extend(list3)
list1
['a', 'b', 'c', ['d', 'e', 'f'], 1, 2, 3]  # but 1, 2, and 3 are separate in the big list

Happy coding! :christmas_tree: And for some holiday-season fun and coding practice, give Advent of Code a try! :santa: