List Comprehension Examples

Survey Results

All participants were asked to either Thumbs up  (thumbs up) or Thumbs down (thumbs down) the following examples for readability.  This was followed up with a discussion of what if mean to be readable for Comprehensions.

Survey Questions

Example 1

return [course for course in courses if course['uuid'] not in courses_with_entitlements]

Example 2

user_run_enrollments = [
    CourseEnrollment.get_enrollment(user, CourseKey.from_string(course_run.get('key')))
    for course_run
    in course_runs
    if CourseEnrollment.get_enrollment(user, CourseKey.from_string(course_run.get('key')))
]

Example 3

upgradeable_enrollments = [
	enrollment
	for enrollment
	in user_run_enrollments
	if enrollment.is_active and enrollment.upgrade_deadline and enrollment.upgrade_deadline > timezone.now()
]

Example 4

self.course_keys = [course.id for course in self.courses]

Example 5

mock_course_grade.side_effect = [
            Exception("Error for {}.".format(student.username))
            if student.username in ['student3', 'student4']
            else mock_course_grade.return_value
            for student in self.students
        ]

Example 6

# Status contains information about Primary/Secondary, so we iterate that list
# But we want to return config for that host, not status (since this is the config module),
# this is the inner loop of the comprehension, where we match on the hostname (could also
# match on _id).
primary   = [ c for m in status['members'] if m['stateStr'] == 'PRIMARY'   for c in rs_config['members'] if m['name'] == c['host'] ]
secondary = [ c for m in status['members'] if m['stateStr'] == 'SECONDARY' for c in rs_config['members'] if m['name'] == c['host'] ]
# we're parsing the config directly here, much simpler
hidden    = [ m for m in rs_config['members'] if m['hidden'] ]

Example 7

course_modes_by_course = {
    course_id: {
        mode.slug: mode
        for mode in modes
    }
    for course_id, modes in unexpired_course_modes.iteritems()
}

Example 8

courseware = [{
    'chapter_name': c.display_name_with_default_escaped,
    'sections': [{
        'section_name': s.display_name_with_default_escaped,
        'clickable_tab_count': len(s.get_children()) if (type(s) == seq_module.SequenceDescriptor) else 0,
        'tabs': [{
            'children_count': len(t.get_children()) if (type(t) == vertical_block.VerticalBlock) else 0,
            'class': t.__class__.__name__} for t in s.get_children()
        ]
    } for s in c.get_children() if not s.hide_from_toc]
} for c in chapters]

Example 9

output_rows = [
    [
        ','.join(status_dict.get(column_name, '')) if (column_name == 'Learners Not Found'
                                                        or column_name == 'Invalid Email Addresses'
                                                        or column_name == 'Preassigned Learners')
        else status_dict[column_name]
        for column_name in output_header
    ]
    for _cohort_name, status_dict in cohorts_status.iteritems()
]
output_rows.insert(0, output_header)

Example 10

return [
    {
        "name": link_name,
        "title": link_title,
        "url": link_url,
    }
    for link_name, link_url, link_title in [
        ("about", marketing_link("ABOUT"), _("About")),
        ("enterprise", marketing_link("ENTERPRISE"),
            _("{platform_name} for Business").format(platform_name=platform_name)),
        ("blog", marketing_link("BLOG"), _("Blog")),
        ("news", marketing_link("NEWS"), _("News")),
        ("help-center", settings.SUPPORT_SITE_LINK, _("Help Center")),
        ("contact", marketing_link("CONTACT"), _("Contact")),
        ("careers", marketing_link("CAREERS"), _("Careers")),
        ("donate", marketing_link("DONATE"), _("Donate")),
    ]
    if link_url and link_url != "#"
]