News Aggregator Tutorial Chapter 3 - Cat

Welcome, @NescafeCoffee!

This kind of construct

 categories = [
    (cat['name'], cat)
    for cat in app_tables.categories.search()
]

is a Python comprehension. It’s a shortcut syntax for constructing a list. It could be written longhand like this:

categories = []
for cat in app_tables.categories.search():
    pair = (cat['name'], cat)
    categories.append(pair)

The for statement creates a variable cat, gives it the 1st value (database table row) from the search(), executes the body of the loop, and then moves on to the next result from search(). This continues until the series of results from search() is exhausted.

So it’s the for statement that actually creates variable cat. You can change its name to anything you like, as long as you change it consistently, and as long as you avoid names that are already in use at that time and place. For example:

categories = []
for category in app_tables.categories.search():
    pair = (category['name'], category)
    categories.append(pair)

Or, using the shorter (comprehension) syntax:

 categories = [
    (category['name'], cat)
    for category in app_tables.categories.search()
]
2 Likes