Introduction
Introduction
In programming, a table is a structured way to organize and display data in rows and columns—just like a spreadsheet. Python doesn’t have a built-in table data structure, but you can easily create and work with tables using lists, dictionaries, or third-party libraries like pandas
, tabulate
, or PrettyTable
.
A basic table in Python is often represented as a list of lists (for rows) or a list of dictionaries (for named columns).
Example (List of Lists):
This format allows us to print, sort, or manipulate tabular data programmatically.
Advantages
Why Are Tables Useful?
-
Organize Data Clearly
Tables provide a clean, readable way to represent structured data, making it easier to understand and work with. -
Enable Data Analysis
Tabular structures are essential in data analysis, where rows represent records and columns represent fields. -
Support Iteration and Automation
Tables make it easy to loop through and process data row-by-row or column-by-column. -
Foundational for CSV and Excel Workflows
Tables are the core structure used in CSV and Excel files—both of which are commonly used for storing and sharing data. -
Useful for Display
When printing data in reports, logs, or terminal UIs, tables make the output neat and easy to read.
Python Code
Python Table Example Code
# Define headers and rows
headers = ["Name", "Age", "Grade", "Passed"]
rows = [
["Alice", 14, "A", "Yes"],
["Bob", 15, "B", "Yes"],
["Charlie", 13, "C", "No"]
]
# Print headers using f-string
print(f"{headers[0]:<10} {headers[1]:<5} {headers[2]:<7} {headers[3]:<7}")
# Print separator line
print("-" * 35)
# Print each row using f-string
for row in rows:
print(f"{row[0]:<10} {row[1]:<5} {row[2]:<7} {row[3]:<7}")
Output:
markdown
Copy
Edit
Name Age Grade Passed
-----------------------------------
Alice 14 A Yes
Bob 15 B Yes
Charlie 13 C No
Key concepts
“{:<10}” means left-align in a space of 10 characters.
*headers and *row unpacks the list into arguments for .format().
Tutorial Video
Tutorial Video
Sample Table
Sample Table
Here is a sample table in 2D python format for testing with the challenges. You can also use the CSV file here
user_data = [ ["id", "first_name", "last_name", "email", "gender", "city"], ["1", "Morty", "Petrina", "[email protected]", "Male", "Hønefoss"], ["2", "Jacquie", "Falkingham", "[email protected]", "Female", "Stockholm"], ["3", "Marcelle", "Balm", "[email protected]", "Female", "Houping"], ["4", "Raviv", "Foulgham", "[email protected]", "Male", "Otuzco"], ["5", "Farlay", "Peer", "[email protected]", "Male", "Huayacundo Arma"], ["6", "Edd", "Siemons", "[email protected]", "Male", "Żabno"], ["7", "Willdon", "Peetermann", "[email protected]", "Male", "Båstad"], ["8", "Stacie", "Belward", "[email protected]", "Female", "Valença do Douro"], ["9", "Cherry", "Farnin", "[email protected]", "Female", "Curridabat"], ["10", "Odessa", "Thurston", "[email protected]", "Female", "Asunción Mita"], ["11", "Walsh", "Gaythwaite", "[email protected]", "Male", "Bordeaux"], ["12", "Effie", "Holehouse", "[email protected]", "Female", "Colcabamba"], ["13", "Sebastian", "Lockley", "[email protected]", "Male", "Comagascas"], ["14", "Danya", "Chambers", "[email protected]", "Female", "Janaúba"], ["15", "Renado", "Klemensiewicz", "[email protected]", "Male", "Oyem"], ["16", "Hadleigh", "Ashbee", "[email protected]", "Male", "Ravne"], ["17", "Faythe", "Brimfield", "[email protected]", "Female", "Põlva"], ["18", "Temp", "Cowerd", "[email protected]", "Male", "Eisen"], ["19", "Enrichetta", "Delamar", "[email protected]", "Female", "Charleston"], ["20", "Justus", "Leteurtre", "[email protected]", "Male", "Rio de Moinhos"], ["21", "Salaidh", "Escalera", "[email protected]", "Female", "Bantarjati"], ["22", "Rachael", "Coneybeer", "[email protected]", "Female", "Glencoe"], ["23", "Lenard", "Wykey", "[email protected]", "Male", "Pasirmukti"], ["24", "Lucie", "Kembery", "[email protected]", "Female", "Uryupinsk"], ["25", "Sancho", "Mallan", "[email protected]", "Male", "‘Attīl"], ["26", "Rozanna", "Leele", "[email protected]", "Female", "Kobe"], ["27", "Hagan", "Bryns", "[email protected]", "Male", "Stockholm"], ["28", "Sigvard", "Raccio", "[email protected]", "Male", "Sihai"], ["29", "Merralee", "Denning", "[email protected]", "Female", "Yanhu"], ["30", "Cobbie", "Scollard", "[email protected]", "Male", "Damao"], ["31", "Neall", "Thwaite", "[email protected]", "Male", "Paris 03"], ["32", "Byran", "Sarll", "[email protected]", "Male", "Shah Alam"], ["33", "Teddie", "Mackilpatrick", "[email protected]", "Male", "Dziadkowice"], ["34", "Sallyanne", "Ellins", "[email protected]", "Female", "Sovetskiy"], ["35", "Wilmette", "Airey", "[email protected]", "Female", "Kuncen"], ["36", "Nicola", "Yearne", "[email protected]", "Male", "Al Mijlad"], ["37", "Tommi", "Marginson", "[email protected]", "Female", "Cibeusi"], ["38", "Nealson", "Gerrelt", "[email protected]", "Male", "Cândido Mota"], ["39", "Dori", "Esh", "[email protected]", "Female", "Arasji"], ["40", "Gus", "Quinnette", "[email protected]", "Male", "Driefontein"], ["41", "Jaime", "Radnage", "[email protected]", "Male", "Lahoysk"], ["42", "Alfons", "Boodell", "[email protected]", "Male", "Tirah"], ["43", "Sheila-kathryn", "Tutill", "[email protected]", "Female", "Bayan Ewenke Minzu"], ["44", "Yolanthe", "Affuso", "[email protected]", "Bigender", "San Miguel"], ["45", "Renata", "Bayston", "[email protected]", "Female", "Karang Kulon"], ["46", "Justinn", "Battson", "[email protected]", "Female", "Dalonghua"], ["47", "Alys", "Ebbing", "[email protected]", "Female", "Stockholm"], ["48", "Theodora", "Avramovsky", "[email protected]", "Genderqueer", "Il’inskiy Pogost"], ["49", "Levin", "Jeafferson", "[email protected]", "Male", "Magomeni"], ["50", "Arlan", "Reddel", "[email protected]", "Male", "Khodzha-Maston"] ]
41
Challenge 41 – Display a Table
Bronze
Write a program that stores the dataset as a list of lists, with the first row as headers. Display the table in a readable format using tab or space separation.
Silver
Adjust your program to neatly align the columns. Each column should use a consistent width that is wide enough for the longest entry.
Gold
Create a reusable function called print_table(headers, rows)
that accepts any list of headers and rows and prints them in a nicely formatted table.
42
Challenge 42 – Improve the Layout and Flexibility
Bronze
Update your print_table()
function so that it calculates the correct column width automatically based on the widest item in each column (including the header).
Silver
Add vertical bars (|
) to visually separate each column. Your printed table should now resemble an actual table with consistent spacing and borders.
Gold
Ensure that your function can handle numbers, strings, and other types gracefully by converting all items to strings before printing.
43
Challenge 43 – Filtering and Sorting the Table
Bronze
Write a function that filters the table by gender (e.g., show only rows where gender == "Female"
). Allow the user to enter the gender to filter by.
Silver
Write a function to sort the table by any column. Let the user choose the column name (like "first_name"
or "city"
) and display the sorted table.
Gold
Allow the user to choose the sort direction (ascending or descending). Add error handling to make sure the sort column exists and works properly.
44
Challenge 44 – Search and Menu System
Bronze
Allow the user to enter a search term (e.g. "Stockholm"
), and highlight any matching rows in the table. Highlighting can be done by adding >>
at the start of the matching rows.
Silver
Create a menu system where the user can:
-
View the full table
-
Filter the table
-
Sort the table
-
Search the table
-
Quit
The program should loop and return to the menu after each action until the user chooses to quit.
Gold
Combine all features: filtering, sorting, and searching. Allow the user to apply multiple operations in sequence and then view the final result using the print_table()
function.
Teacher Resources
Teacher Resources
Mockaroo – Generator Synthetic Data
Great for generating sample data to play with tables
If students are struggling with the CSV reader then they can load the list data directly in Python to save time and complexity.