Python Tips: Adding Numeric Lists
Be default, Python does not include a method to add two numeric lists. If you have two lists and you use the +
operator on them, it actually concatenates them. So if you write this code:
list_a = [1, 2, 3]
list_b = [4, 5, 6]
list_c = list_a + list_b
print(list_c)
The output is this:
[1, 2, 3, 4, 5, 6]
That’s probably because in Python lists can contain different data types. For example, you could have a list containing an integer, a string and a boolean like this: crazy_list = [1, "bobby", True]
. So it makes sense that Python cannot assume what you mean by “adding” two lists so it defaults to concatenating.
Now you’re probably scratching your head and thinking, “What do I do if I really do want to add two lists numerically?” You have two options: 1) you can write your own code to add two numeric lists, or 2) you can use the NumPy library which is built for numerical operations on data structures.
Let’s get loopy
Just for fun, let’s write a loop to create a new list that is the sum of two numeric lists. Before we start, let’s review the syntax of the for
loop in Python. If we were to write it out in pseudocode it would look something like this:
for <some variable> in <some iterable object>:
<do something>
The variable does not have to be defined before hand and, technically, neither does the iterable object but you need to take note of that keyword, iterable. That object after the in
needs to be a sequence of numbers (i.e. something that you can loop over). For our purposes, we will create another list that represents the number of items in the two lists that we want to add. And in order to create a list of the appropriate length, we will use another built-in method in Python: the len()
method. The len()
function takes an object and returns an integer that is the number of items in that object. For our example, we only need to know the length of one of the lists but it would be good practice to check that both lists are of the same length before attempting to perform the calculation. We will put the length in a variable named list_length
.
list_length = len(list_a)
print(list_length)
Which returns the value 3
. Now we can take that value and use it to create the sequence that is required by the for
loop. We do this by using the built-in function range()
. This function takes an integer as input and returns an “immutable sequence of numbers”. We won’t bother creating another variable to hold the range. Instead, we’ll just use it directly in the for
loop like this:
for i in range(list_length):
Get to the fun part, already
Ok. Ok. Now that you understand how to setup a for
loop, all that’s left is to flesh out the steps to sum the items in our two lists and place them in a new list. Let’s first re-define list_c
to be an empty list like this: list_c = []
. Now we can use the body of the for
loop to do our summing and appending to the new list like this:
for i in range(list_length):
list_c.append(list_a[i] + list_b[i])
print(list_c)
This output of which is:
[5, 7, 9]
What if I don’t want to write my own?
As easy as it was to write that loop, you do have the option of installing and using the NumPy library. I won’t get into installing here because that could probably be a whole post on its own. Instead, I’m going to assume that you have NumPy installed and all you need is the code to add two lists. So here it is:
import numpy as np
array_a = np.array([1, 2, 3])
array_b = np.array([4, 5, 6])
array_c = array_a + array_b
print(array_c)
The output from this is the same as for our loop:
[5 7 9]
Notice, though, that you didn’t have to find the length of the lists and then create a sequence of numbers for the loop; NumPy took care of all that for you. One important difference between default Python and the NumPy library is that NumPy expects that your list items be of the same type. That’s why libraries like NumPy work; they are tailored for a specific use case.
Conclusion
If you can’t find a built-in function to do what you want, it’s easy to write your own code in Python to get the desired results. Looping through lists requires you find the length of the list and then use that to create a number sequence. And lists in default Python can have any type in them but using libraries like NumPy can get you to your destination quicker if you don’t mind installing them. Happy scripting!