TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python List Extend Explained
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python List Extend Explained

Last updated: Apr 23, 2024 10:02 pm
By Meenakshi Agarwal
Share
6 Min Read
Python List Extend Method Explained with Examples
Python List Extend Method Explained with Examples
SHARE

In this tutorial, you’ll gain insights into the Python list Extend method, complete with illustrative examples showcasing its application on various sequences.

Contents
Extend() Method SyntaxExtend() Function FlowchartList Extend Method ExamplesList to a ListSet to a ListString to a ListKey Facts4 Exercises on Python List Extend MethodCombine Two ListsAdd User Inputs to a ListMerge and Sort NumbersFlatten a List

Important to note: The syntax provided in the following section pertains to Python 3, but it can be adapted to suit any other version of Python you may be using.

To Learn about Lists – Read Python List

Understand the List Extend Method

As we learned from previous tutorials, we can append elements to a list using the append method.

The append works fine when you want to add a single element or a list. But when you wish to append an individual letter from a word or an array of single-digit numbers, then it becomes impossible to achieve. Hence, the extend method comes into the scene to address this limitation.

Extend() Method Syntax

This method updates the list by adding elements to the end. They can be a word or a number, etc. When you call this method, it traverses through the arguments and pushes them into the list one by one to the tail end.

Hence, the number of elements appended is the same as the number of arguments passed. It takes only one parameter and does not have a return value.

Its syntax is as follows:

List_name.extend(element)

After the Python extend method gets called, you will get the updated list object.

Extend Method Time Complexity

It has a time complexity that is proportional to the length of the list that we want to add.

Extend() Function Flowchart

When we pass the element to the extend method as an argument, it gets iterated, and the value from each iteration gets appended to the list.

The flowchart below attempts to explain it in a diagram:

Python List Extend Method Flowchart

List Extend Method Examples

While you use this method, consider the following points in mind.

a. When you add a “list” or “set” to a list, each element in the list gets iterated and appended to the tail end.

b. When you add a “string” to a list, the letters of the string get iterated and appended to the tail.

List to a List

targetList = ["Python", "CSharp", "Java", "GoLang", "Angular"]
listToExtend = ["C", "C++"]
targetList.extend(listToExtend)
print(targetList)
# ['Python', 'CSharp', 'Java', 'GoLang', 'Angular', 'C', 'C++']

Set to a List

targetList = ['Spain', 'France', 'Italy', 'New Zealand']
listToExtend = {'Germany', 'Switzerland'}
print(type(listToExtend))
# <class 'set'>
targetList.extend(listToExtend)
print(targetList)
# ['Spain', 'France', 'Italy', 'New Zealand', 'Germany', 'Switzerland']

String to a List

stringsList = ['P', 'Q', 'R']
stringsList.extend('jklmn')
print(stringsList)
# ['P', 'Q', 'R', 'j', 'k', 'l', 'm', 'n']

Also Read: How to use Python List Insert() Method

Key Facts

Here’s a summary of important facts about the List Extend method in Python presented in a table format for easy understanding:

FactDescription
Method Nameextend()
PurposeTo append elements from an iterable (e.g., another list) to an existing list, effectively extending it.
InputAccepts a single argument, which is the iterable containing elements to be added to the existing list.
Modification in PlaceYes, it modifies the original list in place and does not return a new list.
Return ValueReturns None as it modifies the list directly.
Examplepython myList = [1, 2, 3]
myList.extend([4, 5])
# Results in myList = [1, 2, 3, 4, 5]
Use CasesIdeal for merging lists or adding elements from an iterable to an existing list without creating a new one.
VersatilityWorks with various iterable types, not just lists (e.g., tuples, strings, other sequences).
Performance ConsiderationsMore efficient than concatenation (+) for large lists due to in-place modification.
List Extend Key Points

4 Exercises on Python List Extend Method

Here are some unique Python exercises where the list.extend() method can be useful:

Combine Two Lists

Problem#1: Given two lists, list1, and list2, combine them into a single list.

Solution:

list1 = [1, 2, 3]
list2 = [4, 5]

list1.extend(list2)

# Result: list1 = [1, 2, 3, 4, 5]

Add User Inputs to a List

Problem#2: Create an empty list, user_list, and use a loop to add three user inputs (e.g., names) to the list.

Solution:

user_list = []

for _ in range(3):
    name = input("Enter a name: ")
    user_list.extend([name])

print(user_list)
# Example input: "Alice," "Bob," "Charlie"
# Result: user_list = ["Alice", "Bob", "Charlie"]

Merge and Sort Numbers

Problem#3: Create two lists, even_numbers and odd_numbers, containing numbers. Merge them into a single list and then sort the merged list.

Solution:

even_numbers = [2, 4, 6]
odd_numbers = [1, 3, 5]

merged_numbers = []
merged_numbers.extend(even_numbers)
merged_numbers.extend(odd_numbers)
merged_numbers.sort()

print(merged_numbers)

# Result: merged_numbers = [1, 2, 3, 4, 5, 6]

Flatten a List

Problem#4: Given a list of lists, nested_list, use list.extend() to flatten it into a single list.

Solution:

nested_list = [[1, 2], [3, 4], [5, 6]]
flat_list = []

for sublist in nested_list:
    flat_list.extend(sublist)

print(flat_list)
# Result: flat_list = [1, 2, 3, 4, 5, 6]

Best,

TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python List Count Method Explained with Examples List Count Method in Python
Next Article Python List Clear Method Explained with Examples List Clear Method in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x