Previous Lesson: Lesson 12: In, Not In, and Operators on Lists in Python

Do more with your lists in Python! In this lesson, you’ll learn about accessing and nesting on lists in Python. You’ll even try each of these out yourself!

Let’s still have this in the file we’ve created and used in our previous lesson: ex11.py. Now, let’s talk about something awesome. Although the things that we’ve learned in the previous lesson was really amazing, it was just more like a kick off for this lesson. Here we go!

Accessing Elements of Lists

To take out (or get) an item or an element from our list, we can simply do this:

Like what we’ve done on Line 3 down to Line 10, we printed out the element using the name of our list, and beside it is a pair of brackets ([]) with a number or index inside.

This is a rule in lists when accessing an element that we need to keep in mind: Just subtract 1 to whatever the th it is. Take Line 8 as an example: The index we used here is [5] but it gets the sixth element, which is True.

You may wonder: “Well, why are lists like that?” That’s because they are considered as what we call zero-based. Which means that they start from zero(0), instead of 1. I know it’s a little confusing. But you’ll get over it soon.

Accessing Letters on a String

We can also access the characters of a string using the same method. Type this in:

Just bear in mind that str is just a variable. And like what I’ve commented out on Line 3, we are taking the seventh element or character from our string using the index [6]. Can you guess what letter will get printed out on our Terminal? Let’s see:

Epic! You see? I think you’re getting it by now. Because things are getting a little bit more interesting. Because we are going to create a list inside a list. And we’ll need to learn how to get the element we want from the list inside the list.

Nesting

Yes, that’s what it’s called–nesting.

And there we’ve just created a list inside a list. This time, as the comment suggests, we want to get the third element inside the fifth element. Let’s get that item!

So the fifth element was: [9.3, 9.4, 9.5] and we used the index [4] to get this list inside our bigger list. But we’re not done yet because inside this list, we want to get the third element, which was the 9.5, using the index [2]. Cool, right?

So that’s it with accessing and nesting on lists in Python! If this is a little more confusing for now, don’t move down to the next topic or else you’ll get dizzy. First, take a break. Then think about the things we’ve just learned about lists. If you’re ready, then let’s crack on!

Next Lesson: Lesson 13. (Part II) Methods and Functions on Lists in Python

3 Replies to “Lesson 13. (Part I) Accessing and Nesting on Lists in Python”

Leave a Reply

Your email address will not be published.