Tutorial

Python Lists and Dictionaries: 10 Assignments With Answers in Python

Master Python lists and dicts — creating, slicing, appending, merging, and iterating — with 10 graded assignments and solutions.

Anuj SainiAug 23, 20264 min read

Lists and dicts carry 80% of early Python logic. This workbook gives you 10 focused assignments — with worked solutions — so indexing, slicing, and key handling become reflex.

Who is this workbook for?

Career-switchers who can read a for loop but still pause on "do I append or extend?" and "why did my dict lookup KeyError?" Pair with Python fundamentals master for strings/regex and String assignments for text twin. For tabular next steps, see Pandas fundamentals.

Ingredients: 10 numbered assignments tied to two YouTube references (Lists Basics, Dictionaries Easy), each with a solution cell.

How do you create, access, and modify lists?

python
# Q1: Create and access
fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # apple — index 0 is first
 
# Q2: Modify index 1
fruits[1] = "orange"
print(fruits)  # ['apple','orange','cherry']
 
# Q3: Append & remove
fruits.append("grape")
fruits.remove("apple")
print(fruits)  # ['orange','cherry','grape']

Rendered output after Q1-Q3: fruits evolves apple/banana/cherry -> apple/orange/cherry -> orange/cherry/grape, showing alias-free reassignment. Question prompt links to Video 1 at 1:17 for .append() vs .remove().

How do slicing and iteration work?

python
# Q4: Slicing — stop is exclusive
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4])   # [1, 2, 3]
print(numbers[-2:])   # [4, 5]  last 2
 
# Loop a list safely
for fruit in fruits:
    print(fruit.title())

The slice 1:4 returns indexes 1,2,3 — the classic off-by-one interview check. Negative -2: means "from second-last to end".

How do you create and use dictionaries?

python
# Q5: Create
capitals = {"USA": "Washington DC", "India": "New Delhi", "China": "Beijing", "Russia": "Moscow"}
print(capitals)
 
# Q6: Access
print(capitals["India"])               # New Delhi
print(capitals.get("France", "Unknown"))  # safe default instead of KeyError
 
# Q7: Update & merge
capitals["France"] = "Paris"
capitals.update({"Japan": "Tokyo", "India": "New Delhi"})  # upsert
print(capitals)

Rendered output: the dict grows from 4 to 6 keys; get avoids the crash the unguided solution often hits on missing keys.

python
# Q8-Q10: Iterate and nest
for country, city in capitals.items():
    print(f"{country}: {city}")
 
# Dict of lists — mini database
students = {"Alice": [85, 90, 78], "Bob": [72, 88, 91]}
print(students["Alice"][1])  # 90 — second score
Feature / Criteria

Gotcha: Mutable Dict Values Shared by Reference

Assigning a = {}; b = a; b['x']=1 mutates a too — both names point to the same object. Copy with dict(a) or a.copy() before independent mutation. The workbook shows a failed grading cell until the copy is added.

What next after you finish?

Use lists to collect pd.read_csv chunks and dicts to hold column dtypes before a DataFrame constructor. Then advance to NumPy foundations for vectorised cousins of the same loops.


Download the Notebook and Practise

This article is a walkthrough of a runnable Jupyter notebook. Download the original .ipynb and run it locally or on Colab — every code block above appears in order.

Download the Lists And Dicts Assignments Notebook

Get the complete .ipynb with outputs — runs on any Python 3.10+ environment with pandas, numpy, and the libraries listed in setup.

Download .ipynb

Continue your track: Data Analyst Roadmap · Python and Pandas Guide · SQL NULL Handbook · SQL JOIN Fan-Out · Topfolio Practice · Data Analyst vs Engineer

Dataset generators where applicable are in courses/workbooks/generators/ — see citations atop for the exact *.py source for this notebook.


Frequently Asked Questions

What is the difference between list append and extend?

append adds one element (even if it is a list); extend iterates and adds each element. fruits.append(['a','b']) nests a list; fruits.extend(['a','b']) adds two items.

Why does dict key lookup fail with KeyError?

Accessing capitals['France'] when 'France' is not a key raises KeyError. Use capitals.get('France', 'Unknown') for a safe default.

How do you slice the last N elements of a list?

numbers[-N:] — negative start means count from the end. numbers[1:4] returns indexes 1,2,3 (stop is exclusive).

Are lists ordered in Python?

Yes — insertion order is preserved. Dicts also preserve insertion order since Python 3.7.

Frequently Asked Questions

What is the difference between list append and extend?

append adds one element (even if it is a list); extend iterates and adds each element. fruits.append(['a','b']) nests a list; fruits.extend(['a','b']) adds two items.

Why does dict key lookup fail with KeyError?

Accessing capitals['France'] when 'France' is not a key raises KeyError. Use capitals.get('France', 'Unknown') for a safe default.

How do you slice the last N elements of a list?

numbers[-N:] — negative start means count from the end. numbers[1:4] returns indexes 1,2,3 (stop is exclusive).

Are lists ordered in Python?

Yes — insertion order is preserved. Dicts also preserve insertion order since Python 3.7.

Anuj Saini

Written by

Anuj SainiFounder & Lead Instructor

Founder at Topfolio with 6+ years in data & analytics across JPMC, Ultrahuman, and high-growth startups. Sat on hiring panels, reviewed 500+ resumes, and writes practical SQL & data guides.