Python .extend()
In Python, the .extend()
method adds the elements of an iterable (like a list, string, or tuple) to the end of the current list. Unlike .append()
, which adds the entire object as a single element, .extend()
adds each element individually.
This makes .extend()
especially useful for combining lists or incorporating multiple values into an existing list.
Syntax
list.extend(iterable)
Parameters:
iterable
: An iterable (like a list, tuple, or string) whose elements are to be added tolist
.
Return value:
The .extend()
method changes the list in place and returns None
.
Example 1: Extending a List with Another List
This example uses .extend()
to add the items from the grocery_new
list to the end of the grocery
list:
grocery = ['blueberries', 'eggs', 'artichoke']grocery_new = ['milk', 'cookies']grocery.extend(grocery_new)print(grocery)
Here is the output:
['blueberries', 'eggs', 'artichoke', 'milk', 'cookies']
Example 2: Extending a List with a Tuple
This example uses .extend()
to add the items from the targets
tuple to the end of the to_do_list
list:
to_do_list = ['respond to email', 'check github']targets = (4, 1, 6, 20)to_do_list.extend(targets)print(to_do_list)
Here is the output:
['respond to email', 'check github', 4, 1, 6, 20]
Codebyte Example: Extending a List with a String
This example uses .extend()
to add the characters of a string to the end of the letters
list:
Frequently Asked Questions
1. What is the difference between .append()
and .extend()
?
.append()
adds the entire object as a single element..extend()
adds elements one by one from the iterable.
2. Does .extend()
return a new list?
No. .extend()
modifies the list in place and returns None
.
3. What happens if I pass a non-iterable object to .extend()
?
If you pass a non-iterable object to .extend()
, you’ll get a TypeError
.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours