Question about brackets

Screen Link:
https://app.dataquest.io/m/169/i%2Fo-bound-programs/3/blocking-tasks

I don’t understand why team is placed between brackets runs = cur.execute(query, [team]).fetchall() Someone please explain

Code:

import sqlite3

memory = sqlite3.connect(':memory:') # create a memory database
disk = sqlite3.connect('lahman2015.sqlite')

dump = "".join([line for line in disk.iterdump() if "Batting" in line])
memory.executescript(dump)

cur = memory.cursor()
query = "SELECT SUM(HR) FROM Batting WHERE teamId=?"
def calculate_runs(teams):
    home_runs = []
    for team in teams:
        runs = cur.execute(query, [team]).fetchall()
        runs = runs[0][0]
        home_runs.append(runs)
    return home_runs

profile_string = "home_runs = calculate_runs(teams)"
cProfile.run(profile_string)

Let me be facetious to better understand your question.

Because otherwise it yields an error.

Hi Bruno,

I would write

runs = cur.execute(query, team).fetchall()

This does lead to an error, but I want to understand why it leads to the error.

It leads to an error because they programmed it that way.

I realize this answer isn’t helpful, so let me change the question:

Why did they program this in such a way that team team can’t be passed in the way that you did?

I can only guess, but I think the motivation for this is as follows.

Consider the query template below.

SELECT SUM(HR)
  FROM Batting
 WHERE teamId=? AND year=?

There are two placeholders; one for teamId and one for year. We would like a way to run code with multiple placeholders, like above.

To identify them all, a natural way is to pass an iterable (like a list) with the values, something like:

cur.execute(query, [team, year])

Hence the need for it to be an iterable and not just a single value.

They could have made the necessary modifications for it to interpret team as [team], but they chose not to for some reason.

I hope this helps.

1 Like

Thanks Bruno, this makes sense and I understand it !