Python Join Lists
Join Two Lists
In Python, you can join lists using various methods depending on what exactly you want to achieve.
Using the + operator:
You can concatenate two lists using the + operator.
Example
list1 = [1, 2, 3] list2 = [4, 5, 6] joined_list = list1 + list2 print(joined_list)
Using the extend() method:
This method adds elements of a list (or any iterable) to the end of the current list.
Example
list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend = (list2) print(list1)
Using list comprehension:
You can also use list comprehension to join lists.
Example
list1 = [1, 2, 3] list2 = [4, 5, 6] joined_list = [x for x in list1] + [x for x in list2] print(joined_list)
Using the append() method in a loop:
You can iterate over one list and append its elements to another list.
Example
list1 = [1, 2, 3] list2 = [4, 5, 6] for item in list2: list1.append(item) print(list1)