.extend()
method is used to add multiple elements to the end of a list. It unpacks the given iterable (like a list, tuple, or set) and appends each element individually.list1.extend(iterable)
list1
: The original list.
iterable
: A sequence (like list, tuple, set, etc.) whose elements will be added.
myCart = ['python', 'agentic']
myCart.extend(['langgraph', 'vector_db'])
print(myCart)
['python', 'agentic', 'langgraph', 'vector_db']
Notice: it added each element from the second list individually (not as a sublist).
append()
:Method | Adds what? | Example | Resulting List |
---|---|---|---|
append() |
Adds the whole item as one element | myCart.append(['a', 'b']) |
['python', 'agentic', ['a', 'b']] |
extend() |
Adds each element separately | myCart.extend(['a', 'b']) |
['python', 'agentic', 'a', 'b'] |
myCart.extend(('js', 'react')) # tuple
myCart.extend({'ml', 'ai'}) # set (order not guaranteed)
.extend()
modifies the original list. It does not return a new list.
It raises TypeError
if a non-iterable is passed (e.g., myCart.extend(123)
is invalid).