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

การเข้าถึงค่า List (Accessing Values of Lists) ใน Python

เพื่อเข้าถึงค่าใน lists ให้ใช้ square brackets สำหรับ slicing พร้อมกับ index หรือ indices เพื่อรับค่าที่มีอยู่ที่ index นั้น

ตัวอย่าง

#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]

ผลลัพธ์ (Output)

เมื่อรันโค้ดข้างต้น จะได้ผลลัพธ์ดังนี้:

list1[0]: physics
list2[1:5]: [2, 3, 4, 5]