Python: expression for x in y.

This is a part of the 100 Days To Offload challenge.

My employer is looking to hire a full-time junior Django developer.

I was going through the Django Admin Cookbook today and came across the following snippet:

return ", ".join([ for child in obj.children.all()

Reads fine but made no sense as it ditches the tabs construct that is so ubiquitous in Python. I usually don’t like such clever one-liners, but learned from it nonetheless. There’s probably more to it than I can see as a Python beginner.

Essentially, the argument passed to str.join(iterable) boils down to:

[expression for x in y]

Let’s expand that with an example:

[person.get_full_name() for person in people]

This will return a sequence (which is an iterable, and in this case a list) by running the given expression for each person returned by the people iterable. It returns a list because of those square brackets around the whole instruction: [].

So, it might return, for a more real world example, something like:

["Jim Harper", "Pam Beesly", "Kelly Kapoor", "Toby Flendorson"]

Update: As Jason McGillivray and Nicola Zangrandi informed me on Mastodon and Twitter respectively, the technical name for this “pattern” is actually list comprehension!

Join the discussion on Mastodon or Twitter.