Junior — Middle
Kuidas erinevad Pythonis listide Append ja Extend meetodid nende eesmärgi ja käitumise poolest?
sobes.tech AI
Vastus AI-lt
In Python lists, the methods append and extend are used to add elements, but they work differently:
-
append(obj)adds a single object to the end of the list as one element. -
extend(iterable)expands the list by adding each element from the given iterable object separately.
Example:
lst = [1, 2, 3]
lst.append([4, 5]) # lst becomes [1, 2, 3, [4, 5]]
lst.extend([6, 7]) # lst becomes [1, 2, 3, [4, 5], 6, 7]
Thus, append adds the entire element as a whole, while extend unpacks the iterable object and adds its elements separately.