List เป็นคอลเลกชันของออบเจ็กต์คั่นด้วยจุลภาค ล้อมด้วย วงเล็บเหลี่ยม [] สมาชิกไม่จำเป็นต้องเป็นชนิดเดียวกัน และซ้ำได้
ตัวอย่าง
>> L1 = ["Raaj", 23, ["Phy", "Che", "maths"], 8.5] >>> L1 ['Raaj', 23, ['Phy', 'Che', 'maths'], 8.5] >>> type(L1)
คุณสมบัติสำคัญ
- Mutable: เพิ่ม ลบ แก้ไข สมาชิกได้
- Ordered: รักษาลำดับการเพิ่ม
- Heterogeneous: เก็บชนิดข้อมูลต่างกันได้
- Allow duplicates: สมาชิกซ้ำได้
- Indexable & Sliceable: ใช้
L[i]และL[start:stop]
วิธีสร้าง List อื่นๆ
>> # list() constructor
>>> list("abc")
['a', 'b', 'c']
>>> list((1, 2, 3))
[1, 2, 3]
>>> list({'a': 1, 'b': 2}) # keys only
['a', 'b']
>>> # List comprehension
>>> [x**2 for x in range(5)]
[0, 1, 4, 9, 16]
>>> # * operator (repeat)
>>> [0] * 5
[0, 0, 0, 0, 0]