how_list_of_tuples_works.py
#list of tuples: result = [("a","b"),("c","d"),("e","f")] #tuple 0: print(result[0][0]) #a print(result[0][1]) #b #tuple 1: print(result[1][0]) #c print(result[1][1]) #d #tuple 2: print(result[2][0]) #e print(result[2][1]) #f
import sqlite3 db = sqlite3.connect('bookshop.db') result = db.cursor().execute("SELECT * FROM books").fetchall() db.close() print(result[1][2]) #category: fiction print(result[1][3]) #description field of tuple number 1
import sqlite3 db = sqlite3.connect('bookshop.db') result = db.cursor().execute("SELECT * FROM books").fetchall() db.close() print(result[0][1]) print(result[0][5]) print("$" + str(result[0][4]))
SELECT * FROM books
" returns all six fields from the books table, the six fields are indexed from 0 to 5:
There are 13 books (tuples) in the bookshop.db table, indexed from 0 to 12 in the result
list variable. It is important to note that the index for both lists and tuples in Python starts at 0 and not 1.
Core Activities:
result
list variable:
Extension Activities:
Harry Potter and the Chamber of Secrets by Rowling, J.K. RRP: $13.95 Half price: $7