[Tutor] Printing a list count - Help

Alan Gauld alan.gauld at btinternet.com
Fri Aug 29 22:24:34 CEST 2014


On 29/08/14 20:17, Derek Jenkins wrote:
> Hi everybody,
>
> I have a list that I want to go through and finally print a total
> count of particular items. In this case, I want to print the result of
> how many A's and B's are in the list.
>
> honor_roll_count = 0
> student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", "A"]
>
> for grades in student_grades:
>      honor_roll_count = honor_roll_count + 1
>      if grades == "A" or grades == "B":
>          print honor_roll_count
>

lists have a count() method.
try this:

honor_roll_count = student_grades.count('A') + student_grades.count('B')

For more complex data sets you could use the itertools groupby function too.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list