From the course: Programming Foundations: Data Structures

Unlock the full course today

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

Search array-like structures

Search array-like structures

- [Instructor] We were able to access specific items in a list or tuple earlier because we knew their index, we knew exactly where they were stored. But what happens when you don't know the index of an item you're searching for, or if the item even exists at all? In most cases, searching is about determining whether a value exists in a list or not. Sometimes you'll also want to know the index of the item or even retrieve the item itself if it's found. The most straightforward solution is to check every item in the list, examining each element to see if it matches the one you're looking for. If you find a match, you return true. If you reach the end of the structure without finding it, you return false. In many languages, you can do this using a for loop to iterate over the list, checking each item at every index. Let's try it in Python. We'll start by creating a list and defining the item we want to search for. Then we'll write a function that looks for the item in the list. If the…

Contents