Python for Databases 1: Values, Variables and Collections
How Python holds one row and a whole table of bike-share data: values, variables, text, lists, tuples and dictionaries, the first step before using SQL from Python.
Last updated:
How does Python hold one day of bike-share data?
In the SQL guide, a table row looked like this: a date, a season, a weather label and a number of rentals.
This lesson shows how Python holds a row, and how it holds the whole list of rows that a query returns.
These lessons teach the Python that the database pages of this course use, each idea where it is first needed.
They start from the beginning and need no earlier programming experience.
This lesson covers values, variables, text, and the collections that hold rows:
lists, tuples and dictionaries. Loops and functions goes over the rows and gives names to pieces of work, and objects and generator expressions reaches the objects behind the ORM (object-relational mapper) that connects tables to Python objects.
Every example on this page runs in your browser: select Run under it.
The first run downloads Python, which takes a few seconds. The boxes of one page share their variables, so run them from top to bottom.
Values, variables and print
A value is a piece of data, such as the number 985 or the text 'Winter'.
A variable is a name that refers to a value. A function is a named action:
you write its name and, between brackets, the values it works on, and it does its job (many functions also give a value back).
To see values on the screen we use the function print: it shows its arguments (the values you put between the brackets):
it puts a space between one value and the next, and moves to a new line at the end.
You create a variable by writing its name, an equals sign and a value.
The assignment itself creates the variable, and you do not write a type:
the type belongs to the value.
rentals = 985 # a whole number
season = 'Winter' # text
working_day = False # a truth value
print(season, rentals, working_day)
Winter 985 False
Reading the example from the top:
- Everything after
#is a comment: Python ignores it. Comments explain the code to people. - The names are free to choose, but they cannot start with a digit or contain spaces; Python programmers write them in lowercase with underscores, such as
working_day.
The type belongs to the value, not to the name. The function type tells you which kind of value a name refers to:
print(type(rentals), type(season), type(working_day))
# the same name can refer to another kind of value
rentals = 985.5
print(type(rentals))
<class 'int'> <class 'str'> <class 'bool'>
<class 'float'>
The word class in the output is the name Python uses for a kind of value; objects and generator expressions explains what a class is.
In these boxes there is a shortcut: when the last line is only a value or a calculation, such as rentals or rentals + 1, the box shows its value even without print (text is shown with quotes, to tell it apart from a number).
Use print for everything else.
The basic kinds of value we use are:
| Type | Name in Python | Example | In SQLite |
|---|---|---|---|
| Whole number | int | 985 | INTEGER |
| Number with a fraction | float | 0.344167 | REAL |
| Text | str (string) | 'Winter' | TEXT |
| True or false | bool | True, False | stored as 1 and 0 |
| No value | NoneType | None | NULL |
None is Python’s way to say “no value here”. When a database returns a NULL, Python receives None.
Practice
Create a variable date with the text '2011-07-04' and a variable rentals with the whole number 6043.
Use three separate print calls to print date, then rentals, then the type of rentals, each on its own line.
# your code here
Show a hint
The type of a value is found with the function type.
Show a solution
date = '2011-07-04'
rentals = 6043
print(date)
print(rentals)
print(type(rentals))
2011-07-04
6043
<class 'int'>
Show a common mistake and why it happens
Here the number is written inside quotes, so Python treats it as text:
date = '2011-07-04'
rentals = '6043'
print(date)
print(rentals)
print(type(rentals))
Quotes turn whatever is inside them into text, even digits. The value '6043' looks the same when printed, but its type is str and not int, so it cannot be added or compared like a number.
Show a common mistake and why it happens
Here all three values go into one print call:
date = '2011-07-04'
rentals = 6043
print(date, rentals, type(rentals))
print with several values writes them on one line separated by spaces.
The task asks for three separate print calls, so that each value appears on its own line.
Text and comparisons
Text can be written between single quotes or between double quotes:'Winter' and "Winter" are the same value. (In SQL, single quotes are the standard for text; in Python you may use either, and a text that contains one kind of quote is easier to write with the other kind.)
An f-string puts values inside text (the f comes from the word formatted).
Start the text with the letter f and write each value inside curly brackets:
Three tools for text appear in the next box. The function len returns the length of the value it receives, and for text the length is the number of characters.
A function and a method do the same kind of job; they differ in where the value goes.
A function takes the value between brackets after its name: len(message).
A method belongs to a value and is written after it, with a dot:message.upper(). The method upper makes every letter a capital letter, and title makes the first letter of each word a capital letter and leaves the rest small (so 'bike share' becomes 'Bike Share'):
date = '2011-01-01'
rentals = 985.5
message = f'On {date} there were {rentals} rentals in the {season}'
print(message)
print(len(message), message.upper())
print(message.title())
On 2011-01-01 there were 985.5 rentals in the Winter
52 ON 2011-01-01 THERE WERE 985.5 RENTALS IN THE WINTER
On 2011-01-01 There Were 985.5 Rentals In The Winter
Text has many more methods: lower makes every letter small, and replace swaps one piece of text for another.
The dot notation appears again in objects and generator expressions.
To compare values, use == (equal), != (not equal), <, >, <= and >=.
A single = assigns a value to a name; a double == asks whether two values are equal.
Combine conditions with and, or and not:
rentals = 985
print(
rentals > 1000, season == 'Winter',
rentals > 1000 or season == 'Winter'
)
print(7 / 2, 7 // 2, 7 % 2)
False True True
3.5 3 1
The last line shows three arithmetic operators: / always gives a number with a fraction, // gives the whole part of the division, and % gives the remainder.
Check yourself: after rentals = 985 and season = 'Winter', what is the value of this expression?
rentals > 1000 and season == 'Winter'
A: True
The thinking: the season is Winter, so the condition is satisfied.
The mistake: and needs both conditions to hold. The first one, rentals > 1000, is false because 985 is smaller than 1000, so the whole condition is false.
B: an error, because a number is compared with text
The thinking: the two sides compare different kinds of values.
The mistake: each side of and is a separate comparison. The left one compares two numbers and the right one compares two texts, so each is allowed.
C: False
Correct: and is true only when both sides are true. Here rentals > 1000 is false, so the result is false whatever the season is.
With or the result would be true, because one true side is enough.
Practice
Create message = 'bike share'. Use three print calls, each on its own line:
first the length of message, then message with every letter a capital letter, then message with only the first letter of each word a capital letter.
# your code here
Show a hint
Two methods change letters to capitals: upper for every letter and title for the first letter of each word.
Show a solution
message = 'bike share'
print(len(message))
print(message.upper())
print(message.title())
10
BIKE SHARE
Bike Share
Show a common mistake and why it happens
Here title() is used also for the line where every letter should be a capital letter:
message = 'bike share'
print(len(message))
print(message.title())
print(message.title())
title() capitalises only the first letter of each word and leaves the others small.
Writing every letter in capitals is a different method, upper(), so the second line is not what the task asks for.
Show a common mistake and why it happens
Here the name is written in quotes inside len:
message = 'bike share'
print(len('message'))
print(message.upper())
print(message.title())
'message' in quotes is the text of the word message, with 7 letters, not the variable.
Without quotes, message is the name of the variable and len returns the length of its value, 'bike share', which has 10 characters including the space.
Tuples and lists: several values in order
A row in the result of a query is several values, one for each column, in the order of the columns in the SELECT.
Python has two collections for values in order.
A tuple is written with round brackets. It is the natural form of a row, and it cannot be changed after it is created.
A list is written with square brackets, and it can grow and change.
A list is the natural form for many rows.
row = (1, '2011-01-01', 'Winter', 985)
rides = [985, 801, 1349, 1562, 1600]
print(row[0], row[3], row[-1])
print(rides[0], rides[1:3], len(rides))
1 985 985
985 [801, 1349] 5
How to read the example:
- The place of a value in a collection is its index. Counting starts at 0:
row[0]is the first value androw[3]is the fourth. A negative index counts from the end, sorow[-1]is the last value. rides[1:3]is a slice: the part of the collection from index 1 up to, but not including, index 3.lenreturns the length of the collection. For a list or a tuple the length is the number of items (values), and for text it is the number of characters.
Lists can change. Tuples cannot. Three functions work on a whole list:sum adds all its values, max returns the largest and min the smallest.
The method append adds a value at the end of a list, and the word in asks whether a value is in a collection:
rides.append(1700) # add a value at the end
rides[0] = 990 # replace a value
print(rides, sum(rides), max(rides), min(rides))
print(1349 in rides)
[990, 801, 1349, 1562, 1600, 1700] 8002 1700 801
True
If you write row[3] = 1000 for the tuple, Python stops with this error:
'tuple' object does not support item assignment
A tuple protects a row from accidental change.
The values of a tuple can be unpacked into separate names in one line, which is how a program usually pulls the values out of a row:
day_id, date, season, rentals = row
print(date, rentals)
2011-01-01 985
The result of a query reaches Python as a list of rows, and each row is a tuple:
a row is a fixed group of values, one for each column, and a tuple expresses that a row does not change.
A list of lists would work too, but it is not what sqlite3 returns.
A value is reached with two indexes: the row first and then the position inside the row:
rows = [
(1, '2011-01-01', 'Winter', 985),
(2, '2011-01-02', 'Winter', 801),
(3, '2011-01-03', 'Winter', 1349),
]
print(len(rows), rows[1], rows[2][3])
3 (2, '2011-01-02', 'Winter', 801) 1349
This is the shape of the answer that a database query returns:
a list of tuples.
Practice
Create a list weekend with the rentals 801 and 985, and add 1349 to it with append.
Then use three print calls, each on its own line: the whole list, its length, and its first value read with an index.
# your code here
Show a hint
Python counts positions from 0.
Show a solution
weekend = [801, 985]
weekend.append(1349)
print(weekend)
print(len(weekend))
print(weekend[0])
[801, 985, 1349]
3
801
Show a common mistake and why it happens
Here the first value is read with the index 1:
weekend = [801, 985]
weekend.append(1349)
print(weekend)
print(len(weekend))
print(weekend[1])
In everyday counting the first item is number 1, but Python starts from 0.
The index 1 is the second value, 985, and the first value is at index 0.
Show a common mistake and why it happens
Here the list is printed before the new value is added:
weekend = [801, 985]
print(weekend)
print(len(weekend))
weekend.append(1349)
print(weekend[0])
Python runs the lines in order. When print runs, the list still has two values, because append comes later.
A list shows only what it holds at that moment.
Dictionaries: values with names
In a tuple you must remember that the fourth value is the rentals.
Unlike a tuple, where a value is found by its position, a dictionary keeps each value under a name, called a key, like a row with column names.
It is written with curly brackets and key: value pairs. Writing day['season'] reads a value by its key.
The method get also reads a value by its key, but when the key is missing it returns the second argument you give it instead of failing:
day = {
'date': '2011-01-01', 'season': 'Winter', 'rentals': 985
}
print(
day['season'], day.get('rentals'),
day.get('weather', 'unknown')
)
day['rentals'] = 990 # change a value
day['working_day'] = False # add a new key
print(day)
Winter 985 unknown
{'date': '2011-01-01', 'season': 'Winter', 'rentals': 990, 'working_day': False}
day['season']reads the value of a key, and fails with an error if the key does not exist.- Assigning to a key that exists changes its value, and assigning to a new key adds it.
A dictionary is also the natural form for a lookup table, such as the service plan of each season (as in the season_plan table of the SQL guide):
plan = {'Winter': 'Reduced service', 'Summer': 'Extra staff'}
print(plan['Summer'], 'Spring' in plan)
Extra staff False
The word in asks whether a key exists.
Check yourself: rows is this list:
rows = [
(1, '2011-01-01', 'Winter', 985),
(2, '2011-01-02', 'Winter', 801),
(3, '2011-01-03', 'Winter', 1349),
]
Which expression gives the season of the second row, 'Winter'?
A: rows[2][2]
The thinking: “the second row” sounds like the number 2, and the season looks like position 2 inside the row.
The mistake: indexes start at 0, so the second row is rows[1].
The expression rows[2] is the third row.
B: rows[1][2]
Correct: rows[1] is the second row, and [2] is the third value inside it, the season.
Counting from 0, the season is at index 2 because the identifier is at index 0 and the date at index 1.
C: rows['season']
The thinking: use the name of the column.
The mistake: a list has numeric indexes only. Names work in a dictionary, so this works for day['season'] but not for a list of tuples.
Practice
Create a dictionary named day with three keys: 'date' with the text '2011-01-01', 'season' with the text 'Winter', and 'rentals' with the number 985.
Print its season. Then change its rentals to 1000, add the key 'weather' with the text 'Clear', and print the whole dictionary.
# your code here
Show a hint
Assigning to a key changes it when it exists and adds it when it does not.
Show a solution
day = {
'date': '2011-01-01', 'season': 'Winter', 'rentals': 985
}
print(day['season'])
day['rentals'] = 1000
day['weather'] = 'Clear'
print(day)
Winter
{'date': '2011-01-01', 'season': 'Winter', 'rentals': 1000, 'weather': 'Clear'}
Show a common mistake and why it happens
Here the new key is written as a new dictionary:
day = {'date': '2011-01-01', 'season': 'Winter', 'rentals': 985}
print(day['season'])
day['rentals'] = 1000
day = {'weather': 'Clear'}
print(day)
Writing day = {...} creates a new dictionary and replaces the old one, with all its keys.
To add a key to the existing dictionary, assign to it with day['weather'] = ....
Show a common mistake and why it happens
Here the new rentals value is written as text:
day = {'date': '2011-01-01', 'season': 'Winter', 'rentals': 985}
print(day['season'])
day['rentals'] = '1000'
day['weather'] = 'Clear'
print(day)
The quotes around 1000 make it text, not a number. It prints with quotes in the dictionary, and it would not behave like a number in a calculation.
Using code that others wrote: import
Python comes with many ready-made tools, grouped in modules.
The statement import makes a module available by its name. The statement from ... import ... brings one name out of a module.
We use import sqlite3 to talk to a database in SQL from Python.
The form from module import * brings in every name that the module offers, which saves writing the module name before each tool.
The next box uses two modules. The module math holds mathematical tools:math.sqrt(x) is the square root of x, and math.pi is the number pi.
The module random holds tools for chance: randint(1, 6) returns a random whole number from 1 to 6, both ends included.
import math
from random import randint
# square root, and the number pi
print(math.sqrt(16), math.pi)
# a random whole number from 1 to 6
die = randint(1, 6)
print(die >= 1 and die <= 6)
4.0 3.141592653589793
True
With import math you write the module name before the dot, as in math.sqrt.
With from random import randint you write the name alone.
Data file formats
Data usually arrives in a file, and the file type tells you how to read it.
Open each box to see what such a file looks like.
Text file: lines of characters
A text file holds characters and nothing else, so any editor can show it.
Every other type below is a text file with an agreed layout.
In Python a file is opened with open, and a with block closes it when the block ends, even if an error occurs.
Looping over an open file gives one line at a time, and the method strip removes the line break at the end of a line:
with open('days.txt', encoding='utf-8') as file:
for line in file:
print(line.strip())
Here file is a name for the open file. The option encoding='utf-8' says how characters are stored, which matters for Hebrew text.
CSV file: a table as text
A CSV file (comma-separated values) writes a table as text: one row per line, with the values of a row separated by commas, and usually the column names in the first line.
It is what a spreadsheet exports, and the file that DB Browser exports looks the same (Export results to CSV).
The one-day tuples of this lesson would look like this:
record_id,observation_date,season,total_rides
1,2011-01-01,Winter,985
2,2011-01-02,Winter,801
3,2011-01-03,Winter,1349
Each line becomes a row, like the tuples above. Python reads such a file with the csv module or with a library for working with tables.
JSON file: names and values, like a dictionary
A JSON file writes values with names, in nested form. It is what most web services send back, and it looks almost like the Python dictionary and list of this lesson, with double quotes around every name and text:
[
{
"record_id": 1,
"observation_date": "2011-01-01",
"season": "Winter",
"total_rides": 985
},
{
"record_id": 2,
"observation_date": "2011-01-02",
"season": "Winter",
"total_rides": 801
}
]
Square brackets hold a list, curly brackets hold names and values (a dictionary), and numbers and text are written as they are.
The module json turns such a file into Python dictionaries and lists, and back.
Practice
Each question has its own code box: write your answer there and select Run.
Open a hint if you are stuck, and the solution only after you try.
Write each answer before you open the solution.
Question 1. The variable row holds this row:
(185, '2011-07-04', 'Summer', 6043)
Write one line that creates the variables day_id, date, season and rentals from it, and one line that uses an f-string to print this text:
On 2011-07-04 there were 6043 rentals
# your answer here
Show a hint
The first line is an unpacking; the second starts with f'On {date} ....
Show a solution
row = (185, '2011-07-04', 'Summer', 6043)
day_id, date, season, rentals = row
print(f'On {date} there were {rentals} rentals')
On 2011-07-04 there were 6043 rentals
Unpacking needs one name for each value in the tuple; with three names for four values Python reports an error.
Show a common mistake and why it happens
Without the f, Python prints the text as it is, and the names in the braces are not replaced:
print('On {date} there were {rentals} rentals')
Question 2. This list holds the rentals of five days:
rides = [985, 801, 1349, 1562, 1600]
Compute their average, rounded to a whole number, with sum, len and the function round, and print it.
# your answer here
Show a hint
The average is the sum divided by the number of values. The call round(x) rounds x to the nearest whole number.
Show a solution
rides = [985, 801, 1349, 1562, 1600]
print(round(sum(rides) / len(rides)))
1259
The sum is 6297 and there are 5 days, so the average is 1259.4, which round turns into 1259.
Show a common mistake and why it happens
The second argument of round is the number of digits after the point.
With 1 the result keeps one digit; without it the result is a whole number:
print(round(sum(rides) / len(rides), 1))
Question 3. Write a dictionary for the row below, with the keys date, season and rentals, and then print only its rentals value.
(3, '2011-01-03', 'Winter', 1349)
# your answer here
Show a solution
day = {
'date': '2011-01-03', 'season': 'Winter', 'rentals': 1349
}
print(day['rentals'])
1349
Show a common mistake and why it happens
print(day) shows the whole dictionary. To print one value, read it with its key, day['rentals']:
print(day)
Keep in mind
- A value has a type (
int,float,str,bool,None); a variable is a name for a value, and one name can refer to different kinds of values over time. printshows values;#starts a comment; an f-string puts values inside text.=assigns and==compares.- A tuple
( )is a fixed row; a list[ ]is a changeable sequence; both are indexed from 0, and the result of a query arrives as a list of tuples. - A dictionary
{ }keeps values under names;Nonestands for theNULLof a database. importmakes the tools of a module available.
Next: loops and functions, which let a program go over all the rows.