I was looking at Flask those days and in their user guide I found a Python snippet as below
@app.route('/')
def show_entries():
cur = g.db.execute('select title, text from entries order by id desc')
entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
return render_template('show_entries.html', entries=entries)
Here
entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
creates a list of entries from the database. It is my first time to know to generate a list with a loop inside the bracket.
Can anyone help me point out where I can find the official intro. for such syntax ? is it only limited to list but not tuple nor anything else?
Many Thanks. S.
The thing is called list comprehension
I think this should be the official docs: http://docs.python.org/tutorial/datastructures.html#list-comprehensions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With