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 trial

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.py
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
MOD
Chris Freeman
Treehouse Moderator 68,423 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!!