From the course: Programming Foundations: Data Structures

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Retrieve data from a list in Python

Retrieve data from a list in Python - Python Tutorial

From the course: Programming Foundations: Data Structures

Retrieve data from a list in Python

- [Instructor] To find the average number of books read per student, we need to access each item in the list and sum the contents. We can do this by using the index we mentioned in array theory. Let's create a variable called item_at_index_3. We can access this item with the list name, so that's student_books_list[3]. This will retrieve the fourth number in the list since indexing starts at zero. In our example, the fourth item is seven. Now it's 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 list. If we do, Python will raise an index out of range error, but let's try it and see what happens. IndexError: list index out of range. This occurs because the program is trying to access an item at a position that's outside the list's limit, hence out of range. So let's comment that out for now. Now, the exact way you initialize an array-like structure or access its elements will vary by…

Contents