Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การทำงานของ Concatenation Operator บน List ใน Python

Concatenation operator สร้าง list ใหม่จาก lists เริ่มต้นตามลำดับที่บวกเข้ามา ไม่ใช่ in-place operation

ตัวอย่าง

list1 = [1, 2, 3]
list2 = ['a', 'b']
list3 = list1 + list2
print(list3)

ผลลัพธ์

[1, 2, 3, 'a', 'b']

วิธีอื่น concatenate 2 lists ใช้ extend หากต้องการ extend in-place

ตัวอย่าง

list1 = [1, 2, 3]
list2 = ['a', 'b']
list1.extend(list2)
print(list1)

ผลลัพธ์

[1, 2, 3, 'a', 'b']

Python 3.5+ ใช้ unpacking operator * สร้าง list จาก 2 lists

ตัวอย่าง

list1 = [1, 2, 3]
list2 = ['a', 'b']
list3 = [*list1, *list2]
print(list3)

ผลลัพธ์

[1, 2, 3, 'a', 'b']