23: Python Programs to concatenate two Lists


Example 1: Using + Operator
num_list_1 = [10, 20, 30, 40]
num_list_2 = [50, 60]
concatenated_list = num_list_1 + num_list_2
print(concatenated_list)
Output:

[10, 20, 30, 40, 50, 60]



Example 2: Using the built-in extend() method from List Class
countries1 = ["USA", "Canada", "Mexico"]
countries2 = ["Germany", "France", "Spain"]
countries1.extend(countries2)
concatenated_list = countries1
print(concatenated_list)
Output:

['USA', 'Canada', 'Mexico', 'Germany', 'France', 'Spain']



Example 3: Using the built-in append() method from List Class
genres1 = ["Rock", "Pop", "Hip Hop"]
genres2 = ["Jazz", "Country", "Reggae"]

for genre in genres2:
    genres1.append(genre)

concatenated_list = genres1
print(concatenated_list)


Example 4: Using the * Operator and List Unpacking
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7]
concatenated_list = [*list1, *list2]
print(concatenated_list)


Reference:
list.append(x): To add an item to the end of the list.

list.extend(iterable):  To extend the list by appending all the items from the iterable.
Documentation: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap