Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I learn this Python bracket operator?

Tags:

python

flask

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.

like image 203
zyzyis Avatar asked Feb 22 '26 15:02

zyzyis


1 Answers

The thing is called list comprehension

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

like image 62
aufziehvogel Avatar answered Feb 25 '26 05:02

aufziehvogel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!