Discover the intricacies of Python programming with Noble Desktop. Learn how to use loops and if statements to filter data, an essential skill for various careers in data analysis and programming.
Key Insights
- Loops are used in Python to iterate through lists of data, such as numbers.
- If statements can be used to identify specific data within this list, such as a certain number.
- When used together, loops and if statements can efficiently filter through large quantities of data, even in the thousands or millions.
- A counter variable can be used to track the frequency of a particular data element in the list.
- Filtered data can be stored in a new list using the append method.
- These methods of filtering data are applicable in various fields, including data analysis and programming.
In this video, we're going to look at how to use Filters in Python
Video Transcription
Hi, my name is Art. I teach Python at Noble Desktop. I hope you watched my other videos because in this video I'm going to explain how to use loops and if statements to filter something.
Let me give an example. Suppose I have a list of numbers: 1,2, 3,4, and many fives (5,5, 5,5, 5). Suppose my job is to get all the fives and maybe count them. How would I do that?
It's pretty simple, but let's break it down into steps. First, we need to iterate through the list. We can do this with a loop or number (or any other variable name) in numbers. Let's print that and see what n is. It's pretty much every number.
Now, in our example, we're looking for fives. How will Python know that the number is five? Python can't just take a look, since the list could be really long (thousands, tens of thousands, or even millions of items). We need to compare.
We can do this with an if statement. We need to use an equal comparison operator (==) and say if n == 5. Since after the colon, we need to use indentation, we can move the print statement within the scope of the if statement. We got all the fives!
Now we need to count them. We need some kind of counter, so let's create a new variable and call it "counter". It will start at zero since we haven't seen any fives yet.
What should we do when the if statement returns true? We need to take the counter and increase it by one. We can print the counter outside of the loop. We got five fives.
There is a shorter syntax that means the same thing. We can use "counter += 1". We can also create a new list to store the fives. Let's call it "fives".
We can use the append method to take that object and add it to the end of the list. At the end of the day, if you print "fives", you'll see that the new list contains just the fives. That's how you filter something.
Thanks for watching! In my other video, I'm going to show you how to sort a string.