今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

Python Day Three – Lists, Indices, and Packing Your Virtual Backpack 🎒

Bonface Thuo 2026年05月29日 17:56 3 次阅读 来源:Dev.to

Welcome back to Day 3, Python dynamic duo! 🚀 If you survived Day 2 , you now know how to create variables and throw strings, integers, floats, and booleans into their own little cardboard boxes. 📦 But what happens when you’re building a game and your character needs an inventory? Or you're making a shopping list app? Creating 50 different variables like item1, item2, item3 will make you want to throw your router out the window. 🪟💻 Today, we are leveling up our storage game. We are moving out of single cardboard boxes and packing a Virtual Backpack: Enter Lists! 🎒🎉 🎒 What is a List? In Python, a List is a data structure used to store a collection of items in one single variable. Think of it like a backpack where you can stuff multiple things inside, keep them in a specific order, and pull them out whenever you need them. Creating a list is simple. You use square brackets [] and separate your items with commas: # Packing our survival backpack 🗺️ backpack = [ " map " , " flashlight " , " water bottle " , " protein bar " ] print ( backpack ) # Prints: ['map', 'flashlight', 'water bottle', 'protein bar'] The coolest part? Python lists don’t care what you put inside. You can mix strings, integers, and booleans all in one single backpack (though usually, it makes the most sense to keep similar things together). 🤯 The First Rule of Coding Club: We Start Counting at Zero! Here is where programming turns your brain upside down. 🧠🙃 If I asked you what the first item in our backpack list is, you’d logically say "map". And you'd be right in human language. But in Python-speak, computer memory starts counting at 0. This is called Indexing. To pull a specific item out of your backpack, you write the name of the list followed by the item's position (index) inside square brackets: backpack = [ " map " , " flashlight " , " water bottle " , " protein bar " ] # Pulling out the items using their index 🔍 print ( backpack [ 0 ]) # Prints: map (The absolute first item!) print ( backpack [

本文内容来源于互联网,版权归原作者所有
查看原文