Thursday, January 16, 2025
HomeProgrammingHow to Merge Two Lists in Python

How to Merge Two Lists in Python

In Python, you can merge two lists using several methods:

  • Using the + Operator: The simplest way to merge two lists is by using the + operator, which combines both lists into one.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list) # Output: [1, 2, 3, 4, 5, 6]

  • Using the extend() Method: The extend() method appends the elements of one list to another in place.
See also  Python Lists

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]

  • Using the itertools.chain() Function: The chain() function from the itertools module allows you to merge lists efficiently.

from itertools import chain
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list(chain(list1, list2))
print(merged_list) # Output: [1, 2, 3, 4, 5, 6]

See also  Understanding Perl's -e Operator

These methods allow for easy and flexible list merging in Python.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x