Adding Elements to an Array
This lesson explains how to add elements to an array data structure, including a walk through on the push and bracket syntax methods.
Guide Tasks
  • Read Tutorial

Now that you know what arrays are and how to select elements from an array, let's walk through how to add elements to the data structure.

It's a pretty common occurrence to have the need to add new items to an array, and most languages offer multiple ways to accomplish this behavior.

Let's continue building out our baseball team management application.

Remember that we have an array of nested arrays that contains a list of players and their positions.

players_and_positions = [
  ["George Springer", "OF"],
  ["Jose Altuve", "2B"],
  ["Carlos Correa", "SS"],
  ["Evan Gattis", "DH"],
  ["Tyler White", "1B"],
  ["Alex Bregman", "3B"]
]

What happens when our roster expands we have to add a new member to the team? Well in a real life team we'd need to assign a locker to them in the clubhouse, give them a number, etc.

Surprisingly it's a similar process in computer science. We also have two ways that we can add elements to an array, one is manual and the other is automated.

Adding elements with the push/append method

The common method name for adding an element to an array is push. I've worked with around a dozen programming languages through the years and just about every language has a push or append method available it's called append in Python.

Let's update our baseball team program and use an append method instead of the manual process.

players_and_positions.append(["Charlie Morton", "P"])

What's Next?

In the next guide we'll walk through how to remove elements from an array.