Where can I learn this Python bracket operator?


Question

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.

1
3
1/24/2012 3:56:15 PM

Accepted Answer

The thing is called list comprehension

I think this should be the official docs: http://docs.python.org/tutorial/datastructures.html#list-comprehensions

3
12/30/2011 3:16:47 PM


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon