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

What is an array?

- Let's jump into our first theoretical data structure, an array. An array is like a row of seats at a movie theater. If you think about a row of seats, you've probably noticed they're numbered zero, one, two, three, et cetera, depending on where they're located in the row. And yes, we're starting our counting at zero. We can consider this row to be a collection of seats that each have the option of being taken with a person sitting in it, or being empty. In other words, each seat can have data in it or no data at all, and the seat is numbered, meaning it has a label that can be used to identify it later. Keeping this idea in mind, let's look at the definition of an array. Formally, an array is a collection of elements where each item is identified by an index or key. Let's break this down. Starting with the first part of that definition, an array consists of a collection of elements. Here is a collection of numbers. In this case, we'll say they're all integers. So how would we group these numbers into a data structure? Well, a data structure is a collection with a defined way to access and store items. This means we would need to define a way to access each item in the collection. To make this an array, we would need an index that identifies each element. Looking at our collection, starting at zero, each number in the array will be associated with a unique numerical index based on its position. In this case, we can say the first number in the array, zero, is at index zero. The second number, two, is at index one. The third number, 18, has index two, and so forth. I find it useful to think of each index as a slot. Thinking in this way, we could say the index three slot has the value 40, and the index four slot has the value 14. If this still seems confusing, let's take a look at the movie analogy again. Imagine a single row of seats in a movie theater. Each seat is associated with a specific index or number that identifies that seat. You have seat zero, one, two, et cetera. Think of our numbers as the values in those seats, the values at those indices. The collection of the values in those seats make up the row, and in essence, our array. You also may have noticed that the positional indexing always starts at zero and ends at the length of the array minus one, or the number of items in the array minus one. This is called zero-based indexing, and many popular programming languages, including Python, use this type of indexing in their arrays. Now, no matter what indexing system you're using, the index is very important. This is how you'll access your data in the array structure. Every programming language provides built-in data structures differently. Python itself does not have a data structure called an array, but it has array-like structures. These include tuples and lists, which we'll explore next in this chapter.

Contents