Adding Arguments
- 03:09
Learn how to make custom functions for efficiency, using lists and using for loops for handling multiple lists.
Downloads
No associated resources to download.
Transcript
Let's say that you have these five lists of investment metrics. Some of them you're investing 100 dollars or 100 million dollars and you're getting a rate of return of 20% for two years, 10% for six years, 22% for three years and so on. And if you want to put that into your future value custom function, you could type all of those values out manually, like we did right here, where I'm just typing in 100.1 and 0.3, but that's not really the most efficient way to do this. It would be even better if you formatted your function so that it could receive a list as an input so that then I could just type metrics one or metrics four and it would automatically give my function all three of those values and my function would be able to take those values and interpret them correctly. So what I can do here is rewrite my future value function, and I'm gonna make it so that it can accept a list as an argument. And here, let's just call it metrics list.
And I'm gonna replace investment growth rate in years with the index that corresponds to each of those metrics. Because as you can see, these five lists, metrics one through five have my investment size, my growth rate, and the number of years all in the same position. So I can say return round because I want that number to be rounded instead of investment, I can just say metrics list. And then the position, the index for investment, which is index zero, replace growth rate with index one and then replace years with index two. And I'm actually going to name this new future value so that we can compare here. I'm gonna call Future Value and then I'm just gonna manually input 100.2 and two, those arguments for our investment are growth rate in the years.
And I'm gonna use the print function because I'm gonna have multiple lines here that I wanna show. I'm also going to print new future value, and I'm just gonna pass that metrics one.
So since metrics one contains those same values, if new future value is working correctly, we should get the same answers.
So that's neat. Now you've created a custom function that can receive a list as an argument and process all of the values in the list automatically without you having to manually type them in. And that saves you a little bit of time. But what if you had a lot of lists? What if you didn't just have five, but what if you had 100 or 1,000 of them? You're not gonna go in and type metric one, metric two metric 999, metric 1,000, right? So what we have in Python is what's called a for loop. That iterates through a large number of inputs and it performs the same action over and over so that you don't have to type in metrics one through 1,000. You can just unleash Python on that Iterable action and it'll complete it for you. So let's dive into for loops and how they work.