The Inventory List
Introducing Python Lists
Sometimes simple variables are just not enough. What if you wanted to store multiple values into one thing? Well, python has a few ways we can go about this! The first such way we're covering here is the python list, as seen here:
Notice that the syntax for creating a list is initially similar to creating any variable. Things get strange pretty quickly, however, when you get to the right side of the = sign. The  is part of the python syntax for creating a list. Whatever you put inside the  will be the contents of your list. Notice that the contents of a list (called items) are each separated by comma. It's important to note that a list can be defined all on one line, but it's often easier to read if you split it up over several lines as I have above. Just make sure each item is separated by a comma.
Take a look at those print statements, particularly those where I indicate a number inside the . A very important thing to note here is that each item in a list is stored at some index in the list. An index is just a place value. These place values start at 0, which can be confusing to get used to. Just take a look at those lines and their corresponding lines of output. You'll get a feel for index values relatively quickly.
How about those strange print lines with the : inside the parentheses? These allow us to do what's called slicing. For now, take a look at the code and corresponding output. Change some of the code and watch how the output changes. The way slicing works should become clearer the more you experiment.
Also note that I have the items in single quotes. That is because I want those values to be taken literally. If I didn't put quotes around them, they'd be interpreted as variable names, which they aren't. Which gives me some ideas for your assignment.
- Get rid of the quotes surrounding each of the items I placed in the inventory list. Run the code. What happened?
- Put the quotes back and add a few more items inside the inventory list.
- Use a print statement and the correct index value to print the 4th element in your inventory list.
- At what index value is the 5th item stored?
- Google "python lists append" and see what you can find about how you can add items to a python list. Once you think you've found a satisfying solution, go ahead and try adding a few elements using what you find. Don't simply hardcode the items into the list. In other words, don't go up into the code where the list is and add items in with some commas.
Join the Dungeon Crawl: A place for programmers to ponder, partake, and peruse postulations pertaining to programming, politics, potions, and pizza.
If you subscribe on Patreon, you will be granted access to the Dojo, a growing collection of quality computer science classes created and actively mantained and frequented by the Dungeon Master!Become a Patron!