Using Python List Insert at the Front and End

The Python List() can handle multiple types of data making it very useful for different applications. The list() can cut down on lines of code and the need for casting or converting data types. This is especially convenient if we have database queries that include different types of data, numbers, decimals or strings.

Python list() Method and Index

Let’s take a quick look at some examples with data and indexing inside a list(). You can copy this code into your (VS Code) IDE and execute it, then change the index references to pull the data you need.
Also, remember the index starts at 0. 🙂

empty = []
numbers = [5, 23, 819, 445721]
characters = ["N","Done","free", "nnnmmm"]
num_float = [3.12, 6.11325, 317.35123]
combo = ["SomeText", 819, 317.35123, "X"]

print(numbers[2])
print(characters[1])
print(num_float[0])
print(combo[3])

Add to beginning of list()

In this case the list is populated manually but how can we add a new value to the front or beginning of the list. This would be the index of zero (0).
If we assign the index of 0, we end up overwriting that value inside the list.

numbers = [5, 23, 819, 445721]
numbers[0] = 333
print(numbers)

After creating the list, use the “insert” method to insert the value at any index point in the list(). The new value will be added and the other items will be retained but “shifted” so to speak. This means the index value for each item will change when you use “insert“.

## List.insert(index, value)
combo = ["SomeText", 819, 317.35123, "X"]
combo.insert(1, "INSERTED")
print(combo)

combo.insert(3, "INSERTED")
print(combo)

Try running this code multiple times, you will see that the “shift” only happens one time if the value is the same. “INSERTED” will be at the 1 and 3 index position… unless you change the value.

combo.insert(3, "INSERTED_2")
print(combo)

Add to end of list()

As we can surmise the next step is to figure out how to add the item to the end if we don’t know the actual number of items. We can use the Python Len() function to get the number of items and the “insert” method.

characters = ["N","Done","free", "nnnmmm"]
characters.insert(1, "INSERTED")
characters.insert(3, "INSERTED_2")

print(len(characters))
print(characters)

The Len() function returns the number of items so it includes the first index of zero (0). So we can use this as the new or “last” position in the list and add it to the insert method.

characters = ["N","Done","free", "nnnmmm"]
characters.insert(1, "INSERTED")
characters.insert(len(characters), "INSERTED_END")

print(characters)

This is great for appending values at the end of the list when needed or for creating an empty list and adding values as the logic progresses.