Python list.extend() function
The list.extend()
method in Python is used to add multiple elements to the end of a list. Unlike list.append()
, which adds a single element, extend()
takes an iterable (such as a list, tuple, or string) and appends each of its elements to the original list. This method modifies the original list in place and does not return a new list.
Syntax
- Parameters:
iterable
: An iterable (like a list, tuple, set, or string) whose elements will be added to the list.
Return Value
- The method does not return a value (
None
is returned implicitly).
Example Usage
Extending a List with Another List:
Extending with a Tuple:
Extending with a String: When extending with a string, each character of the string is added as a separate element:
Using
extend()
in a Loop: You can also useextend()
to add elements from an iterable dynamically:Combining Lists: You can use
extend()
to combine two lists:
Summary
list.extend()
is a powerful method for adding multiple elements to a list from any iterable.- It modifies the original list in place and allows for the combination of various data types.
- This method is particularly useful when you want to merge lists or append multiple elements at once without nesting them in a new list.