Search⌘ K
AI Features

Introduction to Array

Explore the concept of arrays in Python, understanding their fixed size and contiguous memory properties. Learn how arrays store data efficiently, how to access elements using zero-based indexing, and see practical applications in web development, data science, game development, and more.

When writing programs, we often need to store a group of related values. Individual variables can only hold one value at a time, which makes them a poor fit for this kind of task. To see why, consider a simple example.

Why do we need an array?

Imagine you just finished a 10-game bowling tournament, and you want to jot down your score from each game. You could create ten separate pieces of paper, one for each score.

Ten separate pieces of paper containing score of each bowling game
Ten separate pieces of paper containing score of each bowling game

But these separate pages would be chaotic to manage. The same problem occurs in programming. To store ten scores, you would have to create ten separate variables, ten separate names to remember, and no easy way to loop through them.

score1 = 120
score2 = 135
score3 = 98
.
.
.
score10= 120
Ten separate variables to store scores of each bowling game

The code would become unworkable as the number of scores grows. This is the core limitation of primitive variables: they can only hold one value at a time, so managing a collection of related values with them quickly becomes impractical.

This problem isn’t unique to bowling scores. Consider the following examples:

  • In gaming, leaderboards need to store and rank multiple player scores in order.

  • In data logging, a weather station records temperature every hour throughout the day.

  • In image processing, every pixel on our screen has a position and a color value that must be tracked.

What all of these share is the same underlying need: store a collection of related values and access any one of them quickly by its position. Individual variables alone cannot do this efficiently.

What is the solution? To derive the solution, consider the bowling game example. Instead of creating ten cards to store the results of individual games, a single scorecard with ten indexed slots is used.

Writing the results of each bowling game on a single card
Writing the results of each bowling game on a single card

In programming, this scorecard is called an array.

What is an array?

By definition, an array stores a collection of elements of the same type in contiguous memory locations. ...