Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Functional Python The Lambda Lambada Recursion

Vincent Zamora
Vincent Zamora
3,872 Points

prerequisite challenge - pres = pres or set()

I am not sure what "pres = pres or set()" this is doing? Is it passing in logic into a variable?

courses = {'count': 2,
           'title': 'Django Basics',
           'prereqs': [{'count': 3,
                     'title': 'Object-Oriented Python',
                     'prereqs': [{'count': 1,
                               'title': 'Python Collections',
                               'prereqs': [{'count':0,
                                         'title': 'Python Basics',
                                         'prereqs': []}]},
                              {'count': 0,
                               'title': 'Python Basics',
                               'prereqs': []},
                              {'count': 0,
                               'title': 'Setting Up a Local Python Environment',
                               'prereqs': []}]},
                     {'count': 0,
                      'title': 'Flask Basics',
                      'prereqs': []}]}

def prereqs(data, pres=None):
    pres = pres or set()

1 Answer

Chris Freeman
Chris Freeman
Treehouse Moderator 68,030 Points

Great question! The line pres = pres or set() is a bit of an idiom.

First, notice that the default value for pres is None. Since the code is intended to be called recursively, the top_level call would not have any initial value to pass, so the argument is not specified.

When entering the function for the first time, since pres is not specified it is set to None. Now to the line in question.

In Python, an or will evaluate "lazily". That is, it will stop evaluating and return the first "truthy" object. If pres is specified, then it will be assigned to the local variable pres. [assignment within a function makes the variable local.] If pres is not specified, then it becomes None, The statement then reads None or set() which the or passes over the None and evaluates set() returning the new empty set.

On subsequent calls to prereqs where pres is specified, the set() portion is not evaluated.

Post back if you have more questions. Good Luck!!