What is the difference between the append and extend methods for a list in Python?
- User
What is the difference between the append and extend methods for a list in Python?
- Assistant
The extend method requires an iterable such as a list as input. When it is called, it will add the elements of the input to the list one at a time, each as a single item in the original list.
The append method can take any type of data as input. When it is called, it will add the entire input to the list as a single item.
Here is an example the illustrates the difference.
# using extend a = ["red", "green", "blue"] b = ["shirt", "shoes", "belt"] a.extend(b) print(a) #displays ['red', 'green', 'blue', 'shirt', 'shoes', 'belt'] # using append a = ["red", "green", "blue"] b = ["shirt", "shoes", "belt"] a.append(b) print(a) # displays ['red', 'green', 'blue', ['shirt', 'shoes', 'belt']]As you can see, lists "a" and "b" each have three items.
In the first example, using extend, the elements of list "b" are added to list "a" each as one item, resulting in a list of six items.
In the second example, using append, the entirety of list "b" is added to list "a" as a single item, resulting in a list of four items.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →