Junior — Middle
What is the difference between adding elements to a list using the append method and concatenating lists?
sobes.tech AI
Answer from AI
The append method (for example, in Python — append, in Java — add for lists) adds a single element to the end of an existing list, modifying it in place.
List concatenation creates a new list by merging the elements of two lists without modifying the original ones.
Example in Java with ArrayList:
import java.util.ArrayList;
ArrayList<String> list1 = new ArrayList<>();
list1.add("a");
ArrayList<String> list2 = new ArrayList<>();
list2.add("b");
// append (add) an element to list1
list1.add("c"); // list1 now ["a", "c"]
// concatenate lists
ArrayList<String> combined = new ArrayList<>(list1);
combined.addAll(list2); // combined ["a", "c", "b"]
Thus, append adds a single element, while concatenation merges lists.