Editing Community Data Science Course (Spring 2015)/Day 2 Followup
From CommunityData
The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then publish the changes below to finish undoing the edit.
Latest revision | Your text | ||
Line 17: | Line 17: | ||
Sure enough, that code will print "4" which is the number of things in the list. | Sure enough, that code will print "4" which is the number of things in the list. | ||
The only thing | The only thing that's possibly new here is the line with <code>counter</code> in it twice. All we're doing in that line is just adding 1 to the variable <code>counter</code> and then replacing the old value with the new, slightly bigger, version. | ||
Of course, instead of that counter and | Of course, instead of that counter and for loop, we could have just used <code>len(names)</code> and it would have done the same! The way this gets powerful is that we begin to combine this. | ||
For example, lets say I wanted to just count the number of names that start with the letter "m". I could combine that counter above with an if statement that checks if the "0th" item in each name (i.e., item in the list) is "m" like this: | |||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
Line 34: | Line 36: | ||
Now, this program will print out "2" (the number of names that start with "m") instead of "4". | Now, this program will print out "2" (the number of names that start with "m") instead of "4". | ||
I can also use append to create a new list from within a for loop. So lets say I wanted to create a new list that contains only those "m" names. In this case, the code I'll write is very similar except I will replace the counter with an empty list (<code>[]</code>) and I'll append things to it every time there's a match. Here's an example: | |||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> |