From the course: Programming Foundations: Data Structures (2023)

Unlock the full course today

Join today to access over 24,400 courses taught by industry experts.

Retrieve data from a list in Python

Retrieve data from a list in Python

- [Instructor] To find the average number of pets per student, we need to be able to access each item in the list so we can sum its contents. We can do this by using the index we mentioned in array theory. Let's create a variable called ITEM_AT_INDEX_THREE. We can access this item with the list name, square brackets, and the number three. This will retrieve the fourth item in the list since indexing starts at zero. The fourth item in the list is two. Now it's very important to remember what indices are valid for a given list. For our list of numbers, we cannot access an index greater than the length of the array. If we do, we'll get an index error that says the index is out of range. Let's try it. We'll access the item at index 100, an index way greater than the length of our list. We'll go to Run and Debug, and run the file. And we get an error. This happens because the program is trying to access a position…

Contents