From the course: Programming Foundations: Data Structures

What is an array?

- Let's jump in to our first theoretical data structure, an array. Think of an array like a row of seats in a movie theater. Each seat is numbered zero, one, two, three, and so on depending on its position in the row. We can think of this row as a collection of seats, where each seat can either be occupied by a person or left empty. Similarly, each spot in an array can hold data or remain empty, and each spot has a position, or an index. That allows us to identify it later. Formally, an array is a collection of elements, where each item is identified by an index or a position. The first part of the definition states that an array consists of a collection of elements. For example, here, a collection of six numbers, which we'll assume are integers. In order for this to be a data structure, there needs to be a defined method for storing and accessing items. For arrays, that's done with indexing. Each number in the array is associated with a unique numerical index based on its position in the array. 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 the 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 these values in those seats make up the row, and in essence, our array. You also may have noticed that the positional indexing always started at zero, and ended at the length that 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 type of indexing system you're using, the index is very important. This is how you'll access your data in the array structure. Now, every programming language provides built-in data structures differently. Python itself does not have a data structure called an array, but it does have array-like structures. These include tuples and lists, which we'll explore throughout this chapter.

Contents