Explain in code difference between Python's list .append and .extend functions.
- User
Explain in code difference between Python's list .append and .extend functions.
Assistant
Here is the code showing the difference between the list.append() and list.extend() methods in Python:
# Create a list my_list = [1, 2, 3] # Append adds an item to the end of the list my_list.append(4) print(my_list) # [1, 2, 3, 4] # Extend iterates over its argument adding each element to the list my_list.extend([5, 6]) print(my_list) # [1, 2, 3, 4, 5, 6] # Append adds one item my_list.append([7, 8]) print(my_list) # [1, 2, 3, 4, 5, 6, [7, 8]] # Extend adds each item from the iterable my_list.extend([[7, 8], [9, 10]]) print(my_list) # [1, 2, 3, 4, 5, 6, [7, 8], [7, 8], [9, 10]]The key difference is that append adds a single item to the end of the list, while extend iterates over its argument adding each element to the list. So extend concatenates its argument onto the list, while append just adds the argument itself as a single element.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.