Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chèn list vào list khác trong Python

List có phương thức extend(), thêm các phần tử từ list truyền vào. extend() nối nội dung seq vào list.

Ví dụ

# append
first_list = [1, 2, 3, 4, 5]
second_list = [6, 7, 8, 9, 10]
first_list.append(second_list)
print("The list pattern using append is : " + str(first_list))

# extend
third_list = [11, 12, 13, 14, 15]
fourth_list = [16, 17, 18, 19, 20]
third_list.extend(fourth_list)
print("The list pattern using extend is : " + str(third_list))

Kết quả

The list pattern using append is : [1, 2, 3, 4, 5, [6, 7, 8, 9, 10]]
The list pattern using extend is : [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]