๐ŸŽ“ A1Learner
๐Ÿ”

DSA Arrays in Python

An array is a row of cells that holds values in order, one value per cell. A Python list is the array used throughout this course.

Reading by index

An index is the position number of a cell, and counting starts at zero. The index -1 names the last cell.

temps = [18, 21, 19, 23, 25, 22, 20]
print(temps[0])
print(temps[3])
print(temps[-1])

Appending at the end

Append places the new value in the next free cell at the end. The earlier values keep their indices, as the unchanged front of the list shows.

temps = [18, 21, 19]
temps.append(23)
print(temps)
print(len(temps))

Inserting in the middle shifts values

Every value from the insert position onward must move one cell over. Four values sit at or after position 1 here, and the printed list shows all four shifted.

temps = [18, 21, 19, 23, 25]
position = 1
shifted = len(temps) - position
temps.insert(position, 99)
print(temps)
print("Values shifted:", shifted)

Example

temps = [18, 21, 19, 23, 25, 22, 20]
print("Days recorded:", len(temps))
print("First day:", temps[0])
print("Fourth day:", temps[3])
print("Last day:", temps[-1])
print("Warmest day:", max(temps))

Key points

  • A Python list is an ordered row of cells, and it plays the role of the array in this course
  • Index: the position number of a cell, counting from zero
  • Reading by index costs one step, however long the list is
  • Appending adds one cell at the end and moves nothing
  • Inserting in the middle shifts every later value one cell over

In this example, one list holds the temperatures of a week, one value per day. The len call counts seven days. Index 0 reads the first day and index 3 reads the fourth day. Index -1 reads the last day without counting from the front. The max call scans the list and reports the warmest day as 25.

Note

A list can hold mixed kinds of values, but array problems in this course keep one kind per list.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Python Playground

Exercise

What does temps[-1] return for a list of temperatures?