PythonLists and tuples
list. extend()
Adds all the items of another collection to the end of a list.
- Returns
None- Changes the original
- Yes
Example
#Python
frontend = ["HTML", "CSS"]
frontend.extend(["JavaScript", "React"])
print(frontend)
tags = ["python"]
tags += ("ai", "data")
tags.extend("ok")
print(tags)Resultsaved result, you can check it
['HTML', 'CSS', 'JavaScript', 'React']
['python', 'ai', 'data', 'o', 'k']
Definition and usage
#The extend(iterable) method adds every item of the given collection to the end of the list, one after another. It works with lists, tuples, sets, strings, and generators.
Unlike append(), it does not nest the collection, it "unpacks" it instead. The += operator on a list works the same way as extend().
Watch out for strings: extend("abc") adds three separate letters, because a string is a collection of characters.
Syntax
#Syntax
list.extend(iterable)Parameters
#iterable
a collection
The items to add.
Good practices
#- To add a single string as one item, use
append(), notextend(). - If you do not want to change the original, combine the lists with the
+operator:new_list = a + b.
Related entries
#- append() vs extend()append() adds exactly one element to the end of a list, even if that element is itself a list, while extend() appends every element of the given collection in turn.
- list.append()Adds one item to the end of a list.
- list.insert()Inserts an item at a chosen position in a list.
- list()Creates a list, either empty or from the items of another iterable.
Spotted a mistake or missing an example? Write to us.