Python: Examples of list comprehension

python-logoPython list comprehension provides a concise and pythonic way of generating lists.  It allows you to select a subset based on a filter and apply a function to each element.

Because although navigating every list entry, filtering certain records, and applying functions to specific fields is doable using basic ‘for’ statements, ‘if’ logic, and temporary variables, it is even easier to implement and maintain by using Python list comprehension.

Consider the following array of student records, which lists a student’s grade point average as well as class enrollment.  In a real-world program, this data structure would probably come from a yaml/json file or API call.  This code and all examples can be found on github.

students = [
  { 'name':'amy', 'gpa': 3.9, 'classes': ['biology','science'] },
  { 'name':'bob', 'gpa': 3.7, 'classes': ['biology','english'] },
  { 'name':'dan', 'gpa': 2.5, 'classes': ['biology','english'] }
]

Here is printing every student’s name using list comprehension:

print("all students: {}\n".format([ student['name'] for student in students ]))

Calculating the average GPA of all students:

average_gpa = sum(student['gpa'] for student in students) / len(students)

Determining the honors students with GPA above 3.5:

honors_students = [ student['name'] for student in students if student['gpa']>3.5 ]

All the students taking Science:

science_students = [ student['name'] for student in students if 'science' in student['classes'] ]

Creating a dictionary (name=GPA) of students:

name_gpa_map = { student['name']:student['gpa'] for student in students }

 

REFERENCES

docs.python.org, list comprehension

realpython.com, when to use list comprehension

stackoverflow.com, create dict with list comprehension

cmdlinetips.com, dicti0nary comprehension

datacamp.com, dictionary comprehension