Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialjohn larson
16,594 Pointsis this logic of comparing len(value) to a count = 0 variable common in python?
or is it just to make us think?
def favorite_Food(fav):
fav_count = 0
favorite = None
for food, stars in fav.items():
if len(stars) > fav_count:
fav_count = len(stars)
favorite = food
return favorite.title()
1 Answer
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsHi John
Yes, its a common way of comparing the length of a list. if i has a list with fruits and wanted to know the quantity of fruits i would do it like so.See below
fruits = []
fruits.append('bananas')
fruits.append('apples')
fruits.append('mangoes')
fruits.append('grapes')
print(len(fruits)) #this would print 4
john larson
16,594 Pointsjohn larson
16,594 PointsHi Andreas, Thanks for responding. I'm aware of comparing lists, but this concept was introduced because there is an undetermined number of lists to be considered. So instead of comparing list to list, the concept is comparing the length of the value of a dict, to the count variable. This determines if the current length of the iterated value is the longest value. This bypasses the need to use an empty list for comparison sake. It works, I was just wondering if it was common. It has been a definite mind bender for me :D
john larson
16,594 Pointsjohn larson
16,594 PointsThe dict to be passed in could look something like:
favorite_food(favorite_foods )