[Python] Concatenate Lists / Merge Lists in Python
.
(1) Concatenating Lists with "+" Operator
(2) Utilizing the Extend() Method
(3) Applying the Itertools.chain() Function
(4) Native Method for List Concatenation (list.append())
(5) List Comprehension to concatenate lists
... ... ...
(1) Concatenating Lists with "+" Operator:
# Sample Code 1
list1 = [10, 11, 12, 13, 14]
list2 = [20, 30, 40]
res = list1 + list2
print ("Concatenated List: " + str(res))
# Concatenated List: [10, 11, 12, 13, 14, 20, 30, 40]
(2) Utilizing the Extend() Method:
Syntax: list.extend(iterable)
# Sample Code 2
list1 = [10, 11, 12, 13, 14]
list2 = [20, 30, 40]
list1.extend(list2)
print ("Concatenated List: ", list1)
# Concatenated List: [10, 11, 12, 13, 14, 20, 30, 40]
(3) Applying the Itertools.chain() Function:
# Sample Code 3
import itertools
list1 = [10, 11, 12, 13, 14]
list2 = [20, 30, 40]
res = list(itertools.chain(list1, list2))
print ("Concatenated List: " + str(res))
# Concatenated List: [10, 11, 12, 13, 14, 20, 30, 40]
(4) Native Method for List Concatenation (list.append()):
# Sample Code 4
list1 = [10, 11, 12, 13, 14]
list2 = [20, 30, 40]
for x in list2:
list1.append(x)
print ("Concatenated List: ", list1)
# Concatenated List: [10, 11, 12, 13, 14, 20, 30, 40]
(5) List Comprehension to concatenate lists:
# Sample Code 5
list1 = [10, 11, 12, 13, 14]
list2 = [20, 30, 40]
res = [j for i in [list1, list2] for j in i]
print ("Concatenated List: " + str(res))
# Concatenated List: [10, 11, 12, 13, 14, 20, 30, 40]
// End
沒有留言:
張貼留言