Summing and NumPy
00:00
In the previous lesson, I introduced you to the reduce()
function. In this lesson, I’ll show you how to get with the notion of adding lists.
00:09
Python includes a function that sums an interable called sum()
. You pass it a list of numbers, and it returns the sum.
00:18
sum()
also takes an optional start
argument that gets used as the starting point of the summation. Here in this example, giving me two more than the nine from before. As all sum()
does is add well, I suspect you know where I’m going with this,
00:36
and here it is in all its glory. There’s only one tricky part here. You have to use the start
argument with an empty list. The default value for start
is zero, which makes sense if you’re actually adding numbers, but you can’t add a number and a list.
00:52 By changing the starting value to an empty list, you’ll be adding lists to lists, which of course isn’t adding at all. I’m not sure whether to think this method is brilliant or insane.
01:02
It does speak to the consistency of Python as a language. Adding isn’t really adding. Operators aren’t really operators. They’re all calls to an underlying method on an object, and everything in Python is an object even the numbers. Since all sum()
does is add things together, it’s kind of consistent that you can add things besides numbers, because add just means call the corresponding object method, which in the case of lists is .extend()
.
01:30 See, both brilliant and insane. Let’s just prove this works, and
01:47 Now, please don’t do this. All you’re going to do is confuse other programmers, but it does work.
01:57 A popular third-party library for doing number crunching is NumPy. NumPy itself is written in a lower-level language than Python, which means it’s quite speedy.
02:06 If you’re doing a lot of math, NumPy can get you a real performance boost. One of the features of NumPy is the concept of an array. This is its own kind of data structure that typically ends up being a little faster than a list.
02:19
On the screen here, I’ve used NumPy’s array
class to store a matrix. No different from the list of lists you’ve seen so far, but here’s the neat part.
02:28
The array
class actually has a .flatten()
method. Calling .flatten()
returns another array object, but well, flat.
02:35 So if you’re doing a lot of number crunching and need flattened things, well, this is another way of accomplishing it.
02:43 Okay, you’ve now seen a whole bunch of ways to flatten a list of lists. It’s time to talk about why you might choose one over the other.
Become a Member to join the conversation.
piovere on May 10, 2024
I don’t think that the
numpy
solution will work for ragged lists (a list of lists with different lengths).