ข้ามไปยังเนื้อหาหลัก
Editor

ลิสต์ใน Python: สร้าง เข้าถึง แก้ไข และวนลูปลิสต์

เริ่มต้น30 นาที8 แบบฝึกหัด145 XP

บทเรียนนี้แปลจากต้นฉบับภาษาอังกฤษRead in EnglishLeer en españolЧитать на русскомLer em portuguêsแจ้งข้อผิดพลาดในการแปล

0/8 แบบฝึกหัด

ลองนึกถึงเพลย์ลิสต์เพลงโปรดของคุณ เพลย์ลิสต์มีเพลงหลายเพลงเรียงตามลำดับที่แน่นอน คุณเพิ่มเพลงใหม่ ลบเพลงเก่า สลับลำดับ หรือข้ามไปเพลงที่ห้าได้

ลิสต์ (list) ใน Python ทำงานแบบเดียวกันเลย ลิสต์คือกลุ่มข้อมูลที่เรียงตามลำดับและเปลี่ยนแปลงได้ทุกเมื่อที่ต้องการ รายการซื้อของ ชื่อนักเรียน คะแนนสูงสุด สีของพิกเซล ลิสต์เป็นหนึ่งในเครื่องมือที่มีประโยชน์ที่สุดใน Python

ในบทเรียนนี้ คุณจะได้เรียนวิธีสร้างลิสต์ เข้าถึงสมาชิกตามตำแหน่ง เพิ่มและลบสมาชิก วนลูปผ่านลิสต์ ตัดช่วงลิสต์ และหลีกเลี่ยงข้อผิดพลาดที่มือใหม่มักทำบ่อยที่สุด

วิธีสร้างลิสต์ใน Python

สร้างลิสต์ได้โดยใส่สมาชิกไว้ใน วงเล็บเหลี่ยม [] แล้วคั่นแต่ละตัวด้วยเครื่องหมายจุลภาค (comma) สมาชิกแต่ละตัวเป็นชนิดใดก็ได้ ทั้งสตริง ตัวเลข ค่าความจริง หรือแม้แต่ลิสต์อื่น

สร้างลิสต์ด้วยวงเล็บเหลี่ยม
# A list of strings
fruits = ["apple", "banana", "cherry"]
print(fruits)
# A list of numbers
scores = [95, 87, 72, 100, 68]
print(scores)
# A list with mixed types
mixed = ["Alice", 15, True, 3.14]
print(mixed)
ผลลัพธ์
['apple', 'banana', 'cherry']
[95, 87, 72, 100, 68]
['Alice', 15, True, 3.14]

สมาชิกแต่ละตัวในลิสต์มีตำแหน่งที่เรียกว่า ดัชนี (index) สมาชิกตัวแรกอยู่ที่ดัชนี 0 ตัวที่สองอยู่ที่ดัชนี 1 ต่อไปเรื่อย ๆ กฎ "เริ่มนับจากศูนย์" นี้ใช้เหมือนกันในภาษาโปรแกรมเกือบทุกภาษา

คุณยังสร้างลิสต์ว่างไว้ก่อน แล้วค่อยเพิ่มสมาชิกทีหลังได้ด้วย วิธีนี้ใช้บ่อยเมื่อยังไม่รู้ล่วงหน้าว่าลิสต์จะมีอะไรบ้าง

ลิสต์ว่างและคอนสตรักเตอร์ list()
# Empty list - two ways to create one
empty1 = []
empty2 = list()
print(empty1) # []
print(empty2) # []
# The list() constructor can also convert other things into lists
letters = list("hello")
print(letters) # ['h', 'e', 'l', 'l', 'o']
ผลลัพธ์
[]
[]
['h', 'e', 'l', 'l', 'o']

วิธีเข้าถึงสมาชิกในลิสต์ด้วยดัชนีใน Python

ถ้าต้องการหยิบสมาชิกตัวเดียวจากลิสต์ ให้ใส่หมายเลขดัชนีไว้ในวงเล็บเหลี่ยมต่อท้ายชื่อลิสต์ อย่าลืมว่าดัชนีเริ่มที่ 0 ไม่ใช่ 1

เข้าถึงสมาชิกด้วยดัชนีบวก
colors = ["red", "green", "blue", "yellow", "purple"]
# Positive indexing (from the front)
print(colors[0]) # red (first item)
print(colors[1]) # green (second item)
print(colors[4]) # purple (fifth item)
ผลลัพธ์
red
green
purple

Python ยังรองรับ ดัชนีติดลบ (negative indexing) ซึ่งนับจากท้ายลิสต์ -1 คือสมาชิกตัวสุดท้าย -2 คือตัวรองสุดท้าย ต่อไปเรื่อย ๆ

เข้าถึงสมาชิกด้วยดัชนีติดลบ
colors = ["red", "green", "blue", "yellow", "purple"]
# Negative indexing (from the end)
print(colors[-1]) # purple (last item)
print(colors[-2]) # yellow (second-to-last)
print(colors[-5]) # red (first item, the long way around)
ผลลัพธ์
purple
yellow
red

ดัชนีติดลบสะดวกมากเมื่อต้องการสมาชิกตัวสุดท้ายแต่ไม่รู้ว่าลิสต์ยาวเท่าไร my_list[-1] ให้สมาชิกตัวสุดท้ายเสมอ

ตรวจความยาวลิสต์เพื่อป้องกัน IndexError
colors = ["red", "green", "blue"]
print(len(colors)) # 3 items
# This works fine:
print(colors[2]) # blue (index 2 = third item)
# This crashes:
# print(colors[3]) # IndexError! Only indexes 0, 1, 2 exist
ผลลัพธ์
3
blue

วิธีแก้ไขลิสต์ใน Python

ลิสต์ เปลี่ยนแปลงได้ (mutable) หมายความว่าแก้ไขได้หลังจากสร้างแล้ว คุณเปลี่ยนสมาชิกทีละตัว เพิ่มสมาชิกใหม่ หรือรวมลิสต์เข้าด้วยกันได้

เปลี่ยนสมาชิกด้วยดัชนี

ถ้าต้องการแทนที่สมาชิกตัวใดตัวหนึ่ง ให้กำหนดค่าใหม่ให้กับดัชนีนั้น ค่าเดิมจะถูกเขียนทับทั้งหมด

แทนที่สมาชิกด้วยดัชนี
fruits = ["apple", "banana", "cherry"]
print(fruits) # ['apple', 'banana', 'cherry']
# Change the second item
fruits[1] = "mango"
print(fruits) # ['apple', 'mango', 'cherry']
ผลลัพธ์
['apple', 'banana', 'cherry']
['apple', 'mango', 'cherry']

เพิ่มสมาชิกด้วย append(), insert() และ extend()

Python มีวิธีเพิ่มสมาชิกลงในลิสต์สามวิธี แต่ละวิธีทำงานต่างกันเล็กน้อย

สามวิธีในการเพิ่มสมาชิก
shopping = ["milk", "eggs"]
# append() adds one item to the END
shopping.append("bread")
print(shopping) # ['milk', 'eggs', 'bread']
# insert() adds one item at a SPECIFIC position
shopping.insert(1, "butter") # Insert at index 1
print(shopping) # ['milk', 'butter', 'eggs', 'bread']
# extend() adds MULTIPLE items from another list
shopping.extend(["cheese", "juice"])
print(shopping) # ['milk', 'butter', 'eggs', 'bread', 'cheese', 'juice']
ผลลัพธ์
['milk', 'eggs', 'bread']
['milk', 'butter', 'eggs', 'bread']
['milk', 'butter', 'eggs', 'bread', 'cheese', 'juice']
append() เพิ่มเป็นสมาชิกตัวเดียว
a = [1, 2, 3]
a.append([4, 5])
print(a)  # [1, 2, 3, [4, 5]]
extend() เพิ่มสมาชิกทีละตัว
a = [1, 2, 3]
a.extend([4, 5])
print(a)  # [1, 2, 3, 4, 5]

วิธีลบสมาชิกออกจากลิสต์ใน Python

เช่นเดียวกับการเพิ่มสมาชิก Python มีหลายวิธีในการลบสมาชิก วิธีที่เหมาะขึ้นอยู่กับว่าคุณรู้ค่าหรือรู้ตำแหน่ง

remove() และ pop()
pets = ["cat", "dog", "fish", "hamster", "dog"]
# remove() deletes the FIRST matching value
pets.remove("dog")
print(pets) # ['cat', 'fish', 'hamster', 'dog']
# pop() removes by INDEX and returns the removed item
removed = pets.pop(1) # Remove index 1
print(removed) # fish
print(pets) # ['cat', 'hamster', 'dog']
# pop() with no argument removes the LAST item
last = pets.pop()
print(last) # dog
print(pets) # ['cat', 'hamster']
ผลลัพธ์
['cat', 'fish', 'hamster', 'dog']
fish
['cat', 'hamster', 'dog']
dog
['cat', 'hamster']

remove() ค้นหาค่าที่ระบุแล้วลบตัวแรกที่เจอ ถ้าไม่มีค่านั้นในลิสต์ Python จะแจ้งข้อผิดพลาด ValueError

pop() ลบตามตำแหน่งและคืนค่าสมาชิกที่ลบออกมาให้ วิธีนี้มีประโยชน์เมื่อต้องใช้สมาชิกนั้นต่อหลังจากลบแล้ว เหมือนการแจกไพ่จากสำรับ

del และ clear()
numbers = [10, 20, 30, 40, 50]
# del removes by index (doesn't return the value)
del numbers[0]
print(numbers) # [20, 30, 40, 50]
# clear() removes ALL items
numbers.clear()
print(numbers) # []
ผลลัพธ์
[20, 30, 40, 50]
[]

วิธีวนลูปผ่านลิสต์ใน Python

สิ่งที่ทรงพลังที่สุดอย่างหนึ่งที่ทำกับลิสต์ได้คือการ วนลูป (loop) ผ่านลิสต์ คือรันโค้ดชุดเดิมหนึ่งครั้งต่อสมาชิกหนึ่งตัว นี่คือวิธีจัดการข้อมูลร้อยตัวโดยไม่ต้องเขียนโค้ดร้อยบรรทัด

ลูป for พื้นฐานกับลิสต์
fruits = ["apple", "banana", "cherry"]
# The basic for loop
for fruit in fruits:
print(fruit)
ผลลัพธ์
apple
banana
cherry

อ่านโค้ดนี้ว่า "สำหรับผลไม้แต่ละอย่างในลิสต์ fruits ให้แสดงผลไม้นั้น" Python หยิบสมาชิกตัวแรก รันโค้ดที่เยื้องไว้ หยิบตัวถัดไป รันอีกครั้ง ทำแบบนี้ไปเรื่อย ๆ จนครบทุกตัวในลิสต์

บางครั้งคุณต้องการ หมายเลขดัชนี พร้อมกับตัวสมาชิกด้วย ฟังก์ชัน enumerate() ให้ทั้งสองอย่าง

ใช้ enumerate() เพื่อได้ทั้งดัชนีและค่า
fruits = ["apple", "banana", "cherry"]
# enumerate() gives you the index AND the item
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
ผลลัพธ์
0: apple
1: banana
2: cherry

คุณยังวนลูปด้วยช่วงของหมายเลขดัชนีได้ด้วย วิธีนี้มีประโยชน์เมื่อต้องเปรียบเทียบหรือแก้ไขสมาชิกตามตำแหน่ง

วนลูปด้วย range และดัชนี
scores = [85, 92, 78, 95, 88]
# Loop using range(len(...))
for i in range(len(scores)):
print(f"Student {i + 1}: {scores[i]}")
ผลลัพธ์
Student 1: 85
Student 2: 92
Student 3: 78
Student 4: 95
Student 5: 88

วิธีตรวจว่ามีสมาชิกอยู่ในลิสต์ Python หรือไม่

คีย์เวิร์ด in ใช้ตรวจว่ามีค่านั้นอยู่ในลิสต์หรือไม่ ผลลัพธ์คือ True หรือ False

ใช้ in และ not in
colors = ["red", "green", "blue"]
print("red" in colors) # True
print("yellow" in colors) # False
# You can use it in if statements
if "green" in colors:
print("Green is in the list!")
# not in checks for absence
if "purple" not in colors:
print("Purple is NOT in the list.")
ผลลัพธ์
True
False
Green is in the list!
Purple is NOT in the list.

วิธีนี้อ่านง่ายกว่าการเขียนลูปค้นหาค่าเองมาก ใช้ in ได้ทุกครั้งที่ต้องการตรวจว่ามีสิ่งใดอยู่ในลิสต์หรือไม่

การตัดช่วงลิสต์ (slicing) ใน Python

การตัดช่วง (slicing) ช่วยให้หยิบ บางส่วน ของลิสต์ได้ แทนที่จะหยิบแค่ตัวเดียว รูปแบบคือ list[start:end] โดยรวม start แต่ ไม่ รวม end

การตัดช่วงลิสต์พื้นฐาน
letters = ["a", "b", "c", "d", "e", "f"]
# Basic slicing: [start:end]
print(letters[1:4]) # ['b', 'c', 'd'] - indexes 1, 2, 3
# Omit start - defaults to beginning
print(letters[:3]) # ['a', 'b', 'c']
# Omit end - defaults to the end
print(letters[3:]) # ['d', 'e', 'f']
# Both omitted - copies the entire list
print(letters[:]) # ['a', 'b', 'c', 'd', 'e', 'f']
ผลลัพธ์
['b', 'c', 'd']
['a', 'b', 'c']
['d', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f']

กฎ "ไม่รวมตัวท้าย" อาจดูแปลกในตอนแรก แต่มีข้อดีอยู่ letters[:3] ให้สมาชิก 3 ตัวพอดี และ letters[3:] ให้ส่วนที่เหลือทั้งหมด ไม่ต้องสับสนว่านับเกินหรือขาดไปหนึ่งตัว

คุณเพิ่มตัวเลขตัวที่สามที่เรียกว่า ระยะก้าว (step) ได้ ตัวเลขนี้บอก Python ว่าจะขยับไปไกลแค่ไหนในการหยิบแต่ละครั้ง: ระยะก้าว 2 จะหยิบสมาชิกเว้นตัว

การตัดช่วงแบบกำหนดระยะก้าว
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [start:end:step]
print(numbers[0:10:2]) # [0, 2, 4, 6, 8] - every other item
print(numbers[::3]) # [0, 3, 6, 9] - every third item
# Negative step reverses the list
print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
ผลลัพธ์
[0, 2, 4, 6, 8]
[0, 3, 6, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

เมธอดของลิสต์ใน Python ที่ใช้บ่อย

ลิสต์ใน Python มีเมธอดในตัวมากมาย ต่อไปนี้คือเมธอดที่คุณจะใช้บ่อยที่สุด

sort(), reverse() และ count()
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# sort() arranges items in order (changes the original list)
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
# reverse() flips the list order
numbers.reverse()
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
# count() tells you how many times a value appears
print(numbers.count(1)) # 2
ผลลัพธ์
[1, 1, 2, 3, 4, 5, 6, 9]
[9, 6, 5, 4, 3, 2, 1, 1]
2
len(), min(), max() และ sum()
scores = [85, 92, 78, 95, 88]
# len() - number of items
print(len(scores)) # 5
# min() - smallest value
print(min(scores)) # 78
# max() - largest value
print(max(scores)) # 95
# sum() - total of all items
print(sum(scores)) # 438
# Calculate the average
average = sum(scores) / len(scores)
print(f"Average: {average}") # Average: 87.6
ผลลัพธ์
5
78
95
438
Average: 87.6

ข้อผิดพลาดที่พบบ่อยเกี่ยวกับลิสต์ใน Python

ลิสต์มีพฤติกรรมบางอย่างที่ชวนสับสนและทำให้มือใหม่แทบทุกคนพลาด ถ้าเข้าใจตั้งแต่ตอนนี้ จะประหยัดเวลาดีบักไปได้หลายชั่วโมงในภายหลัง

Aliasing: ทั้งสองชื่อชี้ไปที่ลิสต์เดียวกัน
# The aliasing problem
original = [1, 2, 3]
alias = original # NOT a copy!
alias.append(4)
print(original) # [1, 2, 3, 4] - original changed too!
print(alias) # [1, 2, 3, 4]
ผลลัพธ์
[1, 2, 3, 4]
[1, 2, 3, 4]
ทำสำเนาให้ถูกต้องด้วย [:]
# The fix: make a real copy
original = [1, 2, 3]
real_copy = original[:] # Slice copy
real_copy.append(4)
print(original) # [1, 2, 3] - original is untouched
print(real_copy) # [1, 2, 3, 4]
ผลลัพธ์
[1, 2, 3]
[1, 2, 3, 4]
ชื่อแฝง (ออบเจกต์เดียวกัน)
a = [1, 2, 3]
b = a         # b IS a
b.append(4)
print(a)      # [1, 2, 3, 4]
สำเนา (คนละออบเจกต์)
a = [1, 2, 3]
b = a[:]      # b is a COPY of a
b.append(4)
print(a)      # [1, 2, 3]

แบบฝึกหัด

ได้เวลาฝึกแล้ว แบบฝึกหัดเหล่านี้ต่อยอดกันไปทีละข้อ จากพื้นฐานไปจนถึงข้อที่ท้าทายขึ้น ลองทำแต่ละข้อด้วยตัวเองก่อนเปิดดูคำใบ้

แบบฝึกหัดที่ 1: สร้างลิสต์และแสดงความยาว
เขียนโค้ด

สร้างลิสต์ชื่อ animals ที่มีสตริงสามตัวนี้: "cat", "dog", "rabbit"

จากนั้นแสดงความยาวของลิสต์ในรูปแบบนี้ให้ตรงทุกตัวอักษร:

3
# Create your list
# Print the length
แบบฝึกหัดที่ 2: เข้าถึงสมาชิกตัวสุดท้ายด้วยดัชนีติดลบ
เขียนโค้ด

มีลิสต์ชื่อเมืองให้มาแล้ว ใช้ ดัชนีติดลบ เพื่อแสดงชื่อเมืองสุดท้ายในลิสต์

ผลลัพธ์ที่ต้องได้:

Tokyo
cities = ["Paris", "London", "New York", "Tokyo"]
# Print the last city using negative indexing
แบบฝึกหัดที่ 3: รายการซื้อของ: เพิ่มและลบสมาชิก
เขียนโค้ด

คุณมีรายการซื้อของอยู่หนึ่งลิสต์ ให้ทำตามขั้นตอนต่อไปนี้ ตามลำดับ:

1. เพิ่ม "bread" ต่อท้ายลิสต์

2. ลบ "milk" ออกจากลิสต์

3. แสดงลิสต์สุดท้าย

ผลลัพธ์ที่ต้องได้:

['eggs', 'cheese', 'butter', 'bread']
shopping = ["eggs", "milk", "cheese", "butter"]
# Step 1: Add "bread" to the end
# Step 2: Remove "milk"
# Step 3: Print the list
แบบฝึกหัดที่ 4: แก้บั๊ก: IndexError
แก้บั๊ก

โค้ดนี้พยายามแสดงสีสุดท้ายในลิสต์ แต่กลับหยุดทำงานด้วย IndexError แก้บั๊กให้โปรแกรมแสดงผล:

purple

คำใบ้: ลิสต์มีสมาชิก 4 ตัว ดัชนีที่ใช้ได้มีอะไรบ้าง

colors = ["red", "green", "blue", "purple"]
print(colors[4])
แบบฝึกหัดที่ 5: หาผลรวมของตัวเลขทั้งหมดด้วยลูป
เขียนโค้ด

เขียนโปรแกรมหาผลรวมของตัวเลขทั้งหมดในลิสต์ด้วยลูป for ห้าม ใช้ฟังก์ชันในตัว sum()

ผลลัพธ์ที่ต้องได้:

150
numbers = [10, 20, 30, 40, 50]
# Calculate the total using a for loop
# Print the total
แบบฝึกหัดที่ 6: หาตัวเลขที่มากที่สุดโดยไม่ใช้ max()
เขียนโค้ด

หาตัวเลขที่มากที่สุดในลิสต์ด้วยลูป for ห้าม ใช้ฟังก์ชันในตัว max()

ผลลัพธ์ที่ต้องได้:

95
scores = [72, 85, 95, 60, 88]
# Find the largest score using a loop
# Print the largest score
แบบฝึกหัดที่ 7: ทายผลลัพธ์: Aliasing ของลิสต์
ทายผลลัพธ์

อ่านโค้ดนี้อย่างละเอียดแล้วทายว่าจะแสดงผลอะไร ลองคิดว่าจะเกิดอะไรขึ้นเมื่อตัวแปรสองตัวชี้ไปที่ลิสต์เดียวกัน

พิมพ์ผลลัพธ์ให้ตรงทุกตัวอักษร (ถ้ามี print หลายครั้ง ให้แต่ละค่าอยู่คนละบรรทัด)

a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(b)
แบบฝึกหัดที่ 8: กลับลำดับลิสต์โดยไม่ใช้ reverse() หรือ [::-1]
เขียนโค้ด

กลับลำดับลิสต์ที่ให้มาด้วยลูป ห้าม ใช้ reverse(), reversed() หรือ [::-1]

ผลลัพธ์ที่ต้องได้:

[5, 4, 3, 2, 1]
original = [1, 2, 3, 4, 5]
# Reverse the list using a loop
# Print the reversed list

สรุป: สิ่งที่ได้เรียนรู้เกี่ยวกับลิสต์ใน Python

เยี่ยมมากที่เรียนมาจนจบบทเรียนนี้ สรุปทุกอย่างที่คุณรู้แล้วมีดังนี้:

แนวคิดทำอะไรตัวอย่าง
สร้างลิสต์เก็บข้อมูลตามลำดับfruits = ["a", "b"]
เข้าถึงด้วยดัชนีหยิบสมาชิกหนึ่งตัวfruits[0], fruits[-1]
แก้ไขสมาชิกเปลี่ยนค่าfruits[0] = "cherry"
append()เพิ่มต่อท้ายfruits.append("date")
insert()เพิ่มที่ตำแหน่งที่ระบุfruits.insert(1, "fig")
remove()ลบตามค่าfruits.remove("a")
pop()ลบตามดัชนีfruits.pop(0)
ลูป forทำงานกับสมาชิกทีละตัวfor f in fruits:
in / not inตรวจว่าเป็นสมาชิกหรือไม่"a" in fruits
การตัดช่วงหยิบบางส่วนfruits[1:3]
sort() / reverse()จัดลำดับสมาชิกใหม่fruits.sort()
len() / sum()นับจำนวนหรือหาผลรวมlen(fruits)

ลิสต์เป็นโครงสร้างข้อมูลที่ใช้บ่อยที่สุดอย่างหนึ่งใน Python โปรแกรมจริงแทบทุกโปรแกรมใช้ลิสต์ ตั้งแต่เว็บแอป งานวิทยาการข้อมูล ไปจนถึงการพัฒนาเกม

บทเรียนถัดไป

ในบทเรียนถัดไป List Comprehension ใน Python คุณจะได้เรียนทางลัดที่ทรงพลังสำหรับสร้างและแปลงลิสต์ในโค้ดบรรทัดเดียว

คุณจะได้เห็นวิธีย่อโค้ดลูป 4 บรรทัดให้เหลือบรรทัดเดียวที่อ่านง่าย และเรียนรู้ว่าเมื่อไรควรใช้ comprehension และเมื่อไรลูปธรรมดาเหมาะกว่า

บทเรียนที่เกี่ยวข้อง

บทเรียนนี้มีประโยชน์หรือไม่