Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

รายการ


Lists มีความคล้ายคลึงกับอาร์เรย์มาก สามารถบรรจุตัวแปรประเภทใดก็ได้ และสามารถบรรจุตัวแปรได้มากเท่าที่ต้องการ นอกจากนี้ยังสามารถวนลูปผ่าน Lists ได้อย่างง่ายดาย นี่คือตัวอย่างวิธีสร้าง List

mylist = [] mylist.append(1) mylist.append(2) mylist.append(3) print(mylist[0]) # prints 1 print(mylist[1]) # prints 2 print(mylist[2]) # prints 3

prints out 1,2,3

for x in mylist: print(x)

การเข้าถึงดัชนีที่ไม่มีอยู่จะทำให้เกิดข้อยกเว้น (ข้อผิดพลาด)

mylist = [1,2,3] print(mylist[10])

Exercise

ในแบบฝึกหัดนี้ คุณจะต้องเพิ่มตัวเลขและสตริงลงใน List ที่ถูกต้องโดยใช้วิธี "append" ของ List คุณต้องเพิ่มตัวเลข 1,2 และ 3 ไปยัง List "numbers" และเพิ่มคำว่า 'hello' และ 'world' ลงในตัวแปร strings

คุณยังต้องเติมตัวแปร second_name ด้วยชื่อที่สองใน List names โดยใช้ตัวดำเนินการวงเล็บ [] โปรดทราบว่าดัชนีเริ่มต้นที่ศูนย์ ดังนั้นหากคุณต้องการเข้าถึงไอเท็มที่สองใน List ดัชนีจะเป็น 1

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy