Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
In Python, you can concatenate two lists using the +
operator. This will create a new list containing elements from both lists in the order they appear.
Here's an example:
list1 = [1, 2, 3] list2 = [4, 5, 6] # Concatenate the lists concatenated_list = list1 + list2 print(concatenated_list)
Output:
[1, 2, 3, 4, 5, 6]
Alternatively, you can use the extend()
method of a list to append the elements of another list to the end of it. This method modifies the original list in-place.
list1 = [1, 2, 3] list2 = [4, 5, 6] # Append the elements of list2 to list1 list1.extend(list2) print(list1)
Output:
[1, 2, 3, 4, 5, 6]
Keep in mind that using the extend()
method will modify the original list, while using the +
operator will create a new list without changing the original lists.
Python concatenate two lists:
list1 = [1, 2, 3] list2 = [4, 5, 6] result = list1 + list2 print(result) # [1, 2, 3, 4, 5, 6]
Extend one list with another in Python:
list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) print(list1) # [1, 2, 3, 4, 5, 6]
List concatenation vs. append in Python:
list1 = [1, 2, 3] list2 = [4, 5, 6] # Using concatenation concatenated_list = list1 + list2 print(concatenated_list) # [1, 2, 3, 4, 5, 6] # Using append for item in list2: list1.append(item) print(list1) # [1, 2, 3, 4, 5, 6]
Python zip() function for concatenating lists:
list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] result = list(zip(list1, list2)) print(result) # [(1, 'a'), (2, 'b'), (3, 'c')]
List concatenation with itertools.chain in Python:
from itertools import chain list1 = [1, 2, 3] list2 = [4, 5, 6] result = list(chain(list1, list2)) print(result) # [1, 2, 3, 4, 5, 6]
Concatenating lists with list comprehension in Python:
list1 = [1, 2, 3] list2 = [4, 5, 6] result = [item for sublist in [list1, list2] for item in sublist] print(result) # [1, 2, 3, 4, 5, 6]
Merging lists using the * operator in Python:
list1 = [1, 2, 3] list2 = [4, 5, 6] result = [*list1, *list2] print(result) # [1, 2, 3, 4, 5, 6]
List concatenation with the += operator in Python:
list1 = [1, 2, 3] list2 = [4, 5, 6] list1 += list2 print(list1) # [1, 2, 3, 4, 5, 6]
Concatenate lists and remove duplicates in Python:
list1 = [1, 2, 3] list2 = [3, 4, 5] result = list(set(list1 + list2)) print(result) # [1, 2, 3, 4, 5]
Append elements from one list to another in Python:
list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) print(list1) # [1, 2, 3, 4, 5, 6]