List Comprehension

We have just looked at how to interact with MongoDB from within our Python programs, and how to retrieve data and print it out from within Python.

This was the program we wrote in the last few pages:

import pymongo

__author__ = "Your Name"

mongodb_uri = "mongodb://127.0.0.1:27017"
client = pymongo.MongoClient(mongodb_uri)
database = client['fullstack']
collection = database['students']

students = collection.find({})

for student in students:
    print(student)

However, we have not looked at how we can retrieve the data from the database and assign all of the data to a variable.

There are two ways to do it. One way does not use list comprehension, and requires more code, and the other does. Let's look at not using list comprehension first.

We could create a variable students_list which we initialise to be a Python list, and then append each of the students to it as we iterate over the Cursor with our for loop:

import pymongo

__author__ = "Your Name"

mongodb_uri = "mongodb://127.0.0.1:27017"
client = pymongo.MongoClient(mongodb_uri)
database = client['fullstack']
collection = database['students']

students = collection.find({})
students_list = []  # Create the empty list

for student in students:
    students_list.append(student)  # Append each student

print(students_list)

This is all good, and it works!

However, it requires adding more lines of code and it is a bit difficult to read. Instead of directly creating a list of students, we have to iterate over our Cursor and .append each other students to our list.

Lets look at list comprehension. I'll give you a couple of unrelated examples first using IDLE:

>>> values_range = [0, 1, 2, 3, 4, 5]
>>> [x for x in values_range]
[0, 1, 2, 3, 4, 5]

>>> [x*2 for x in range(10)]
[0, 2, 4, 6, 8, 10]

Read the first example as "get the value x for each x inside values_range, and make it part of a new list".

What that does is create a temporary variable x, and assign to it the first value of values_range. What we are putting in the new list is just x (this is the first x we encounter). We are telling Python we want a new list by enclosing this for-loop-like syntax inside square brackets.

Read the second example as "get the value x*2 for each x inside values_range, and make it part of a new list".

Just as above, but this time multiplying x by two before putting it in the new list.

Using list comprehension with our data Cursor

We know we can iterate over our Cursor object, as we have done with a for loop.

We want to get each of the values in our Cursor and put them in a new list, unmodified.

I think you can do this! Try, and then continue reading once you've attempted it.

Since we want the unmodified values to go into a new list, we could just do as the first list comprehension example above:

import pymongo

__author__ = "Your Name"

mongodb_uri = "mongodb://127.0.0.1:27017"
client = pymongo.MongoClient(mongodb_uri)
database = client['fullstack']
collection = database['students']

students = collection.find({})
students_list = [student for student in students]

print(students_list)

In my case, this prints something like the following:

[{'name': 'Jose', 'mark': 75}, {'name': 'Rolf', 'mark': 85}]

There are two students in there: 'Jose' and 'Rolf'.

Now that we've got list comprehension set up, it is easy for us to not get the entire student. For example, we might only want the marks that they got (say, to calculate an average):

import pymongo

__author__ = "Your Name"

mongodb_uri = "mongodb://127.0.0.1:27017"
client = pymongo.MongoClient(mongodb_uri)
database = client['fullstack']
collection = database['students']

students = collection.find({})
marks_list = [student['mark'] for student in students]

print(marks_list)

This would print out the following:

[75, 85]

Hopefully I've convinced you of the power and flexibility of list comprehension. Let's move on to Object-Oriented Programming!

results matching ""

    No results matching ""