Adding Items to Lists

Concepts covered: List Modification

Lists change size while a program runs. The append method adds 1 item to the end, in place: the list itself grows and no new list comes back. Call it with a dot after the list's name and the new item in parentheses.

shopping = ["milk", "bread"]
print("Before:", shopping)

shopping.append("eggs")
print("After first append:", shopping)

shopping.append("cheese")
print("After second append:", shopping)

shopping.append("butter")
print("Final:", shopping)
Before: ['milk', 'bread']
After first append: ['milk', 'bread', 'eggs']
After second append: ['milk', 'bread', 'eggs', 'cheese']
Final: ['milk', 'bread', 'eggs', 'cheese', 'butter']

After 3 calls, shopping holds 5 items, each new one landing after the previous. The order of the calls becomes the order in the list, so append is the right tool whenever items arrive one at a time and arrival order is the order you want to keep.

Building a list in a loop

The most common way to fill a list: start with [], loop, and append each value as you compute it. The loop below squares the numbers 1 through 5 and the list grows by 1 on every pass. Nothing prints until the loop ends, because the point is to keep the results rather than show them.

squares = []

for num in range(1, 6):
    squared = num * num
    squares.append(squared)

print(squares)
[1, 4, 9, 16, 25]

The same shape with an if inside keeps only the values that pass a test. The loop below walks the numbers 1 to 10 and appends the ones divisible by 2, so the result has 5 items while the source still has 10. The source list is never changed; a new list collects the matches.

source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = []

for number in source:
    if number % 2 == 0:
        evens.append(number)

print(evens)
[2, 4, 6, 8, 10]

The accumulator works with a while loop as well, when the number of passes is not known in advance. The loop below starts at 3, doubles the value on each pass, and appends every value below 100. The list ends with 6 items because the seventh value, 192, fails the test.

values = []
n = 3
while n < 100:
    values.append(n)
    n = n * 2
print(values)
print(len(values))

Output:

[3, 6, 12, 24, 48, 96]
6

Inserting at a position

insert takes 2 arguments: the index where the new item should sit, and the item itself. Everything from that index onward shifts 1 place to the right to make room, so the item that used to be at index 1 answers to index 2 after the insert.

letters = ["a", "c", "d"]
print("Before:", letters)

# Insert "b" at index 1
letters.insert(1, "b")
print("After insert at 1:", letters)
Before: ['a', 'c', 'd']
After insert at 1: ['a', 'b', 'c', 'd']

Index 0 puts the item at the front, which is how an urgent request jumps a queue: the 3 existing items each move 1 place right and the new one takes index 0.

queue = ["second", "third", "fourth"]
print("Before:", queue)

# Insert at the beginning
queue.insert(0, "first")
print("After:", queue)
Before: ['second', 'third', 'fourth']
After: ['first', 'second', 'third', 'fourth']
nums = [1, 2, 3]
nums.insert(10, 99)
print(nums)
nums.insert(0, 0)
print(nums)
print(len(nums))

Output:

[1, 2, 3, 99]
[0, 1, 2, 3, 99]
5

An insert index beyond the end raises no error: Python places the item at the end, as append would. Watch for this, because a typo in the index produces a list that looks almost right. The second insert at 0 pushes all 4 items along and the length reaches 5.

append(item)
  • Adds at the end
  • Takes 1 argument
  • Never shifts other items
  • Use when arrival order is the order you want
insert(index, item)
  • Adds at a chosen index
  • Takes 2 arguments, index first
  • Shifts later items right by 1
  • Use when the position must be chosen

Index first, item second

insert reads its first argument as the position and its second as the item, always in that order. On a list of numbers, swapping them raises no error: both arguments are integers, so Python accepts either order and quietly does something else.

a = [1, 2, 3]
a.insert(0, 5)
print(a)

b = [1, 2, 3]
b.insert(5, 0)
print(b)

Output:

[5, 1, 2, 3]
[1, 2, 3, 0]

The first call puts 5 at the front. The second puts 0 at the end, because index 5 lies beyond the end of a 3-item list. With a string item the swap fails loudly instead: an index must be a whole number, so names.insert("Zed", 0) raises a TypeError before the list changes.

About this lesson

This section is part of the Lists: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.