xxxxxxxxxx
list1 = [1,2]
list1 = [3,4]
concat_list1 = list1 + list2 # [1,2,3,4]
concat_list2 = list1.extend(list2) # [1,2,3,4]
concat_list3 = list1.append(list2) # [1,2,[3,4]] <-- list2 is considered 1 element
xxxxxxxxxx
a = [1, 2, 3]
b = [4, 5]
# method 1:
c = a + b # forms a new list with all elements
print(c) # [1, 2, 3, 4, 5]
# method 2:
a.extend(b) # adds the elements of b into list a
print(a) # [1, 2, 3, 4, 5]
xxxxxxxxxx
sum([[1, 2, 3], [4, 5, 6], [7], [8, 9]],[])
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
xxxxxxxxxx
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print(t1)
['a', 'b', 'c', 'd', 'e']
xxxxxxxxxx
""" There are 3 methods: '+', list.append, list.extend() """
# '+'
list_one = [11, 12, 13]
list_two = [14, 15, 16]
answer = list_one + list_two
--> answer: [11,12,13,14,15,16]
# 'list.append' adds items indivudually
# WARNING it treats a list as 1 item
first_list = [1, 2, 3, 4, 5]
second_list = [6, 7, 8, 9]
first_list.append(second_list)
--> first_list: [1, 2, 3, 4, 5, [6, 7, 8, 9]]
# 'extend' adds to the end, only works when both are lists
first_list = [1, 2, 3, 4, 5]
second_list = [6, 7, 8, 9]
first_list.extend(second_list)
--> first_list: [1, 2, 3, 4, 5, 6, 7, 8, 9]
xxxxxxxxxx
sample_list1 = [0, 1, 2, 3, 4]
sample_list2 = [5, 6, 7, 8]
result = sample_list1 + sample_list2
print ("Concatenated list: " + str(result))
xxxxxxxxxx
# There are many methods to do list concatenation
# Method 01
test_list1 = [1, 4, 5, 6, 5]
test_list2 = ['p', 'q', 'r', 's']
for i in test_list2 :
test_list1.append(i)
print(test_list1)
# Method 02
test_list1 = [1, 4, 5, 6, 5]
test_list2 = ['p', 'q', 'r', 's']
test_list3 = test_list1 + test_list2
print(test_list3)
# Method 03
test_list1 = [1, 4, 5, 6, 5]
test_list2 = ['p', 'q', 'r', 's']
res_list = [y for x in [test_list1, test_list2] for y in x]
print(res_list)
# Method 04
test_list1 = [1, 4, 5, 6, 5]
test_list2 = ['p', 'q', 'r', 's']
test_list1.extend(test_list2)
print(test_list1)
# Method 05
test_list1 = [1, 4, 5, 6, 5]
test_list2 = ['p', 'q', 'r', 's']
res_list = [*test_list1, *test_list2]
print(res_list)
# Method 6
import itertools
test_list1 = [1, 4, 5, 6, 5]
test_list2 = ['p', 'q', 'r', 's']
res_list = list(itertools.chain(test_list1, test_list2))
print(res_list)
xxxxxxxxxx
# define two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# concatenate the lists
new_list = list1 + list2
print(new_list) # print as [1, 2, 3, 4, 5, 6]
# extend list1 with the elements of list2
list1.extend(list2)
print(list1) # print as [1, 2, 3, 4, 5, 6]