0

Python - How come the length of this function is 1?

my_courses = {'course1': 'html', 'course2': 'css'} def pyc(**dict): result = [] for kw in dict.keys(): for i in dict[kw]: if i in 'python': result.append(dict[kw]) break return result print(len(pyc(**my_courses))) # how did we get an output of 1? From my understanding: - we're passing {'course1': 'html', 'course2': 'css'} into the pyc function - in the outer for loop, course 1 and course2 are the items (kw) in dict.keys() - in the inner for loop, dict is the name of a list (with course1 and course2 as list items) - the if statement's condition is "if course1 or course2 is in the string 'python' (DON'T UNDERSTAND THIS) --> if the condition is true, we append course1 and course2 to the local result list - the local result list is returned as the value for pyc(**my_courses) The len() function returns the number of items in an object. This means only one of course1 or course2 had met the if statement's condition. --> it turns out that print(pyc(**my_courses)) outputs ['html'] ---> so course1 had met the condition. But why?

9th Oct 2020, 10:22 PM
Solus
Solus - avatar
3 odpowiedzi
+ 4
When kw was 'course1', dict[kw] was 'html' so i was taking each letter of 'html' in turn. As, in the very first iteration, 'h' was in python, 'html' was added to result and the inner loop broken. Since no characters of 'css' were present in 'python', nothing else was added. result just had 1 element at the end.
9th Oct 2020, 10:29 PM
Russ
Russ - avatar
+ 1
Yes, if you wanted to iterate over the characters in the actual key, your inner loop would have read for i in kw:
9th Oct 2020, 10:50 PM
Russ
Russ - avatar
0
Oh okay, so we're evaluating the characters of the VALUES of the keys specified by kw, and NOT evaluating the keys themselves
9th Oct 2020, 10:46 PM
Solus
Solus - avatar