Python Arrays

In Python the everyday "array" is really the built-in list, an ordered, resizable collection that holds a sequence of items.

Many languages ship a dedicated array type, but in Python the collection most people reach for when they need an array is the list. A list keeps its items in order, lets you change it after it is created, and can grow or shrink as your program runs. You can store numbers, strings, or even mixed types in the same list, and you refer to any item by its position, called an index.

Creating an array and reading its items

You build a list by placing comma-separated values inside square brackets. Indexing starts at 0, so the first item lives at index 0 and the last item at length minus one. Negative indexes count backward from the end, which makes reaching the final item easy without knowing the length.

Create a list and access items by index

cities = ["Delhi", "Mumbai", "Chennai", "Kolkata"]

print(cities[0])     # Delhi (first item)
print(cities[-1])    # Kolkata (last item)
print(len(cities))   # 4

for city in cities:
    print(city)

Changing, adding, and removing items

Because lists are mutable, you can overwrite an item by assigning to its index. To grow the list, append() adds a single item to the end and insert() places one at a chosen position. To shrink it, remove() deletes the first matching value while pop() removes an item by index and hands it back to you.

Modifying the contents of a list

scores = [90, 75, 60]

scores[1] = 80          # change the second item
scores.append(100)      # add to the end
scores.insert(0, 50)    # add at the front
scores.remove(60)       # delete the value 60
last = scores.pop()     # remove and return the last item

print(scores)   # [50, 90, 80]
print(last)     # 100
MethodWhat it doesExample
append(x)Adds x to the end of the listnums.append(9)
insert(i, x)Inserts x before index inums.insert(0, 9)
remove(x)Deletes the first item equal to xnums.remove(9)
pop(i)Removes and returns item at i (last if i is omitted)nums.pop()
len(list)Returns how many items the list holdslen(nums)
Note: If you need a true numeric array for math-heavy work, look at the standard library array module or the third-party NumPy library. For general programming, a list is almost always the right choice.
  • Lists are ordered: items keep the position you gave them.
  • Lists are mutable: you can change, add, and remove items after creation.
  • Indexes start at 0, and negative indexes count from the end.
  • A single list can mix types, though keeping one type is usually clearer.

Exercise: Python Arrays

What element does the negative index `my_list[-1]` refer to?