🐍 Python
Beginner
What is the difference between append() and extend() in Python lists?
Answer
append(item) adds a single item to the end of a list. If the item is a list itself, it is added as a nested list: my_list.append([4, 5]) → [..., [4, 5]] — the length increases by 1. extend(iterable) adds each element of the iterable individually to the end: my_list.extend([4, 5]) → [..., 4, 5] — the length increases by the iterable's length. extend accepts any iterable (list, tuple, string, range). Related: insert(index, item) inserts at a specific position. + operator creates a new list. += modifies in place (equivalent to extend). Use append for single items, extend for multiple items. list1 + list2 creates a new list without modifying either — prefer extend for performance when modifying in place.