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

Python Lists: คู่มือครบวงจร สร้าง, เข้าถึง, Manipulate, Sort, Copy

List ใน Python เป็น Ordered, Mutable Collection ใช้ Square Brackets [] รองรับ Mixed Types

1. สร้าง List

# Literal
colors = ["red", "green", "blue"]

# Constructor
colors = list(("red", "green", "blue"))

# Mixed Types
mixed = ['a', True, 1, 1.0, [1, 2]]  # ✅ ได้

# List Comprehension
squares = [x**2 for x in range(10)]  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

2. เข้าถึง Items

colors = ["red", "green", "blue", "orange", "yellow", "white"]

# Index (0-based)
colors[0]    # 'red'
colors[2]    # 'blue'

# Negative Index
colors[-1]   # 'white'
colors[-2]   # 'yellow'

# Slicing [start:stop:step]
colors[1:4]      # ['green', 'blue', 'orange']
colors[:3]       # ['red', 'green', 'blue']
colors[3:]       # ['orange', 'yellow', 'white']
colors[::2]      # ['red', 'blue', 'yellow']
colors[::-1]     # ['white', 'yellow', 'orange', 'blue', 'green', 'red']

3. แก้ไข Items

colors = ["red", "green", "blue", "orange"]
colors[3] = "yellow"
print(colors)  # ['red', 'green', 'blue', 'yellow']

4. วนลูป List

colors = ["red", "green", "blue", "orange"]

# Basic
for color in colors:
    print(color)

# With Index
for i, color in enumerate(colors):
    print(f"{i}: {color}")

5. เพิ่ม Items

colors = ["red", "green", "blue", "orange"]

# append() - เพิ่มท้าย
colors.append("yellow")
# ['red', 'green', 'blue', 'orange', 'yellow']

# insert(index, item) - เพิ่มที่ Index
colors.insert(2, "purple")
# ['red', 'green', 'purple', 'blue', 'orange', 'yellow']

# extend() - เพิ่มหลายตัว (Iterable)
colors.extend(["pink", "brown"])
# หรือ colors += ["pink", "brown"]

6. ลบ Items

colors = ["red", "green", "blue", "orange", "yellow"]

# remove(value) - ลบค่าแรกที่เจอ (ValueError ถ้าไม่มี)
colors.remove("orange")

# pop(index) - ลบและคืนค่าที่ Index, pop() = ลบตัวสุดท้าย
colors.pop(1)   # ลบ 'green' คืน 'green'
colors.pop()    # ลบ 'yellow' คืน 'yellow'

# del - ลบโดย Index หรือ Slice
del colors[0]           # ลบ Index 0
del colors[1:3]         # ลบ Slice
del colors              # ลบตัวแปร List ทั้งตัว

# clear() - ลบทั้งหมด
colors.clear()  # []

7. ความยาว และ Count

colors = ["red", "green", "red", "orange"]
len(colors)           # 4
colors.count("red")   # 2

8. Sort และ Reverse

colors = ["red", "green", "blue", "orange"]

# sort() - In-place (แก้ไข List ตัวเอง)
colors.sort()
print(colors)  # ['blue', 'green', 'orange', 'red']

# sort(reverse=True)
colors.sort(reverse=True)
print(colors)  # ['red', 'orange', 'green', 'blue']

# sorted() - คืนค่า List ใหม่ (ไม่แก้ต้นฉบับ)
original = ["red", "green", "blue"]
new_sorted = sorted(original)
print(original)    # ['red', 'green', 'blue'] (ไม่เปลี่ยน)
print(new_sorted)  # ['blue', 'green', 'red']

# Custom Sort Key
words = ["apple", "pie", "banana"]
words.sort(key=len)  # เรียงตามความยาว
# ['pie', 'apple', 'banana']

9. Reverse (กลับลำดับ)

colors = ["red", "green", "blue", "orange"]
colors.reverse()
print(colors)  # ['orange', 'blue', 'green', 'red']

# reversed() - คืน Iterator (ไม่แก้ต้นฉบับ)
for c in reversed(colors):
    print(c)

10. Copy List

colors = ["red", "green", "blue"]

# Shallow Copy
new_list = colors.copy()           # Method
new_list = colors[:]               # Slice
new_list = list(colors)            # Constructor
new_list = [*colors]               # Unpacking (3.5+)

# ❌ Shallow Copy Problem
nested = [[1, 2], [3, 4]]
shallow = nested.copy()
shallow[0].append(99)
print(nested)  # [[1, 2, 99], [3, 4]] แก้ได้! (Inner List ร่วมกัน)

# ✅ Deep Copy
import copy
deep = copy.deepcopy(nested)

11. รวม List

colors = ["red", "green", "blue"]
numbers = [1, 2, 3]

# + Operator (สร้าง List ใหม่)
combined = colors + numbers
# ['red', 'green', 'blue', 1, 2, 3]

# extend() (In-place)
colors.extend(numbers)
# colors กลายเป็น ['red', 'green', 'blue', 1, 2, 3]

Methods Cheatsheet

MethodคำอธิบายIn-place?
append(x)เพิ่มท้าย 1 Item✅
extend(iterable)เพิ่มหลาย Item✅
insert(i, x)แทรกที่ Index i✅
remove(x)ลบ Value แรกที่เจอ✅
pop(i)ลบและคืนค่า Index i✅
clear()ลบทั้งหมด✅
index(x)หา Index แรกของ x❌
count(x)นับจำนวน x❌
sort()เรียงลำดับ✅
reverse()กลับลำดับ✅
copy()Shallow Copy❌ (New List)

บทความเกี่ยวข้อง