Reputation: 82470
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
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