Nafiul Islam
Nafiul Islam

Reputation: 82470

How does this single line for loop work in Python? [list comprehension]

Here is the code sample:

from django.shortcuts import render_to_response
import MySQLdb

def book_list(request):
    db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost')
    cursor = db.cursor()
    cursor.execute('SELECT name FROM books ORDER BY name')
    names = [row[0] for row in cursor.fetchall()]
    db.close()
    return render_to_response('book_list.html', {'names': names})

The line in particular is:

names = [row[0] for row in cursor.fetchall()]

I just want to understand, how does this line in particular, I understand this is a shorthand way of doing things, but could someone provide how the long version would look like?

Upvotes: 2

Views: 813

Answers (1)

StuGrey
StuGrey

Reputation: 1477

That line is a list comprehension. Here is a 'long' version.

names  = []

for row in cursor.fetchall():
    names.append(row[0])

Upvotes: 5

Related Questions