Exercise 34: Accessing Elements of Lists

Lists are pretty useful, but unless you can get at the things in them they aren't all that good. You can already go through the elements of a list in order, but what if you want say, the fifth element? You need to know how to access the elements of a list. Here's how you would access the first element of a list:

animals = ['bear', 'tiger', 'penguin', 'zebra']
bear = animals[0]

You take a list of animals, and then you get the first (1st) one using 0?! How does that work? Because of the way math works, Python starts its lists at 0 rather than 1. It seems weird, but there are many advantages to this, even though it is mostly arbitrary.

Ready To Learn To Code?

If you enjoyed the sample so far, then you can continue learning by purchasing Learn Python 2 The Hard Way, or Buying Learn Python 3 The Hard Way for 29.99. You'll receive all 52 exercises in PDF and HTML formats, plus videos teaching you each exercise. This course has helped 12 million people learn to code since 2010, so it can help you too. If you want to see more samples then try the Appendix A: Command Line Crash Course. If you already purchased this book then you can download the videos at account page or view the paid HTML version.

Need To Learn For Free?

My Learn Ruby The Hard Way is still free to read for anyone who needs to learn to code. Ruby is a perfectly fine alternative to Python, and works just as well as a first language. If you can't afford Learn Python The Hard Way then read Learn Ruby The Hard Way for free.

Buy The Python 2 Course

When you buy directly from the author, Zed A. Shaw, you'll get a professional quality PDF and hours of HD Video, all DRM-free and yours to download.

$29.99

Buy The Python 2 Course Pre-Order The Python 3 Course Instead

Try a free sample of Learn Python the Hard Way right here, video lectures not included.