Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🐍 Week 1 – Python for Data Science  ·  Day 05

Day 5: Lists, Tuples, Dictionaries & Sets

⏱ 2 hours📶 Beginner🎯 100% self-study
Day 5 / 60

✅ Today you will learn

  • Lists: index, slice, add, remove, sort
  • Tuples for fixed records
  • Dictionaries: key → value lookups
  • Sets for unique values
  • A list of dictionaries – the shape of real data

🏢 In the real world

An API from a delivery app returns orders as JSON – a list of dictionaries like {"order_id": 101, "city": "Pune", "amount": 450}. Before pandas, you must be comfortable reading and summarising exactly this structure.

Four containers at a glance

TypeSyntaxOrderedChangeableDuplicatesUse for
list[1, 2, 3]YesYesYesA column of values
tuple(1, 2)YesNoYesA fixed record, e.g. (lat, lon)
dict{"a": 1}Yes*YesKeys uniqueLookups, one record
set{1, 2}NoYesNoUnique values, membership

Lists

orders →14990-52991-4159992-36493-224994-1
Positive index from the left, negative from the right
Python
orders = [1499, 299, 15999, 649, 2499]
print(orders[0], orders[-1])          # first, last
print(orders[1:4])                    # slice: index 1, 2, 3
print(orders[:2], orders[-2:])        # first two, last two
orders.append(899)                    # add at end
orders.insert(0, 120)                 # add at position 0
orders.remove(299)                    # remove a value
print(orders, len(orders))
print(sorted(orders), sorted(orders, reverse=True)[:3])
print(sum(orders), max(orders), min(orders))
1499 2499 [299, 15999, 649] [1499, 299] [649, 2499] [120, 1499, 15999, 649, 2499, 899] 6 [120, 649, 899, 1499, 2499, 15999] [15999, 2499, 1499] 21665 15999 120

Tuples – records that must not change

Python
office = ("Bengaluru", 12.9716, 77.5946)     # city, latitude, longitude
city, lat, lon = office                       # unpacking
print(city, lat, lon)
try:
    office[0] = "Mysuru"
except TypeError as e:
    print("Tuples cannot change:", e)
Bengaluru 12.9716 77.5946 Tuples cannot change: 'tuple' object does not support item assignment

Dictionaries – key → value

Python
student = {"name": "Priya", "class": 12, "marks": [95, 97, 91]}
print(student["name"], student.get("city", "not given"))
student["city"] = "Jaipur"                 # add / update
student["class"] = "12-A"
print(student)
print(list(student.keys()))
for key, value in student.items():
    print(f"{key:6} -> {value}")
Priya not given {'name': 'Priya', 'class': '12-A', 'marks': [95, 97, 91], 'city': 'Jaipur'} ['name', 'class', 'marks', 'city'] name -> Priya class -> 12-A marks -> [95, 97, 91] city -> Jaipur
Python
gst_rate = {"Grocery": 5, "Fashion": 12, "Electronics": 18, "Books": 0}
cart = [("Atta 10kg", "Grocery", 459), ("Earbuds", "Electronics", 1499), ("Kurta", "Fashion", 899)]
for item, cat, price in cart:
    rate = gst_rate[cat]
    print(f"{item:10} {cat:12} ₹{price:5} + {rate:2}% = ₹{price * (1 + rate / 100):,.2f}")
Atta 10kg Grocery ₹ 459 + 5% = ₹481.95 Earbuds Electronics ₹ 1499 + 18% = ₹1,768.82 Kurta Fashion ₹ 899 + 12% = ₹1,006.88

Sets – unique values

Python
visitors_mon = {"u1", "u2", "u3", "u5"}
visitors_tue = {"u2", "u3", "u4"}
print("Unique cities:", sorted(set(["Pune", "Delhi", "Pune", "Agra", "Delhi"])))
print("Both days   :", sorted(visitors_mon & visitors_tue))   # sorted() = fixed order
print("Any day     :", sorted(visitors_mon | visitors_tue))
print("Only Monday :", sorted(visitors_mon - visitors_tue))
print("u4" in visitors_mon)
Unique cities: ['Agra', 'Delhi', 'Pune'] Both days : ['u2', 'u3'] Any day : ['u1', 'u2', 'u3', 'u4', 'u5'] Only Monday : ['u1', 'u5'] False
MondayTuesday
Returning visitors = Monday ∩ Tuesday
ℹ️ Sets have no order

Printing a set can show items in a different order each run. Wrap it in sorted() when you need a stable, readable order.

List of dictionaries: real data shape

Python
orders = [
    {"id": 101, "city": "Pune",   "category": "Grocery",     "amount": 450},
    {"id": 102, "city": "Delhi",  "category": "Electronics", "amount": 15999},
    {"id": 103, "city": "Pune",   "category": "Fashion",     "amount": 1299},
    {"id": 104, "city": "Mumbai", "category": "Grocery",     "amount": 780},
    {"id": 105, "city": "Delhi",  "category": "Grocery",     "amount": 320},
]
city_total = {}
for o in orders:
    city_total[o["city"]] = city_total.get(o["city"], 0) + o["amount"]
print(city_total)
big = [o["id"] for o in orders if o["amount"] > 1000]
print("Big orders:", big)
top = max(orders, key=lambda o: o["amount"])
print("Top order:", top["id"], top["city"], top["amount"])
{'Pune': 1749, 'Delhi': 16319, 'Mumbai': 780} Big orders: [102, 103] Top order: 102 Delhi 15999
Python
from collections import Counter
categories = ["Grocery", "Electronics", "Fashion", "Grocery", "Grocery", "Fashion"]
c = Counter(categories)
print(c)
print(c.most_common(2))
Counter({'Grocery': 3, 'Fashion': 2, 'Electronics': 1}) [('Grocery', 3), ('Fashion', 2)]
💡 This is exactly a DataFrame

A list of dictionaries with the same keys is a table: each dict is a row and each key is a column. On Day 10 you will turn it into a pandas DataFrame with one line: pd.DataFrame(orders).

Copy trap

Python
a = [10, 20, 30]
b = a              # same list, two names!
b.append(40)
print(a)
c = a.copy()       # real copy
c.append(50)
print(a, c)
[10, 20, 30, 40] [10, 20, 30, 40] [10, 20, 30, 40, 50]

🏅 Job skills unlocked today

✔ Slice and sort lists✔ Store records in dictionaries✔ Find unique and common values with sets✔ Summarise a list of dictionaries

Practice tasks

🏋️ Practice – do it yourself

Task 1: From marks = [56, 78, 91, 45, 88, 67] print the top 3 marks and the average of the rest.
Show solution
Python
marks = [56, 78, 91, 45, 88, 67]
s = sorted(marks, reverse=True)
print("Top 3:", s[:3], "| rest avg:", sum(s[3:]) / len(s[3:]))
Top 3: [91, 88, 78] | rest avg: 56.0
Task 2: Using the orders list of dictionaries above, find the total amount per category.
Show solution
Python
orders = [{"category": "Grocery", "amount": 450}, {"category": "Electronics", "amount": 15999},
          {"category": "Fashion", "amount": 1299}, {"category": "Grocery", "amount": 780}, {"category": "Grocery", "amount": 320}]
total = {}
for o in orders:
    total[o["category"]] = total.get(o["category"], 0) + o["amount"]
print(total)
{'Grocery': 1550, 'Electronics': 15999, 'Fashion': 1299}
Task 3: Two classes took a quiz. Class A: Aman, Priya, Rahul, Sneha. Class B: Priya, Kabir, Sneha. Print students in both, and in only one class.
Show solution
Python
a = {"Aman", "Priya", "Rahul", "Sneha"}
b = {"Priya", "Kabir", "Sneha"}
print("Both:", sorted(a & b))
print("Only one:", sorted(a ^ b))
Both: ['Priya', 'Sneha'] Only one: ['Aman', 'Kabir', 'Rahul']

Quick quiz

🧠 Quick Quiz – test yourself

1. orders[-1] gives…
Negative indexes count from the end.
2. Which container cannot be changed after creation?
Tuples are immutable.
3. d.get("x", 0) returns 0 when…
get returns the default when the key is missing – no KeyError.
4. set([1, 1, 2, 3, 3]) is…
A set keeps only unique values.
5. b = a then b.append(9). What happens to a?
Both names point to the same list; use a.copy() for a real copy.

Interview corner

💼 Interview Corner

List vs tuple – when to use which?

Use a list for a collection that grows or changes (a column of values). Use a tuple for a fixed record whose parts have meaning by position, such as coordinates or a (key, value) pair; tuples can also be dictionary keys.

Why is checking membership faster in a set than in a list?

A set uses a hash table, so "x in s" takes about the same time regardless of size (O(1) on average). A list must be scanned item by item (O(n)).

Summary

  • list = ordered, changeable column of values; slice with [start:stop].
  • tuple = fixed record; dict = key → value lookup; set = unique values.
  • A list of dicts is a table – the bridge to pandas.
  • Use .copy() when you need an independent copy.
➡️ Next

Day 6: read and write CSV and JSON files, handle errors gracefully and use Python modules.

Frequently Asked Questions

Are dictionaries ordered?
Yes, since Python 3.7 dictionaries keep insertion order.
What is Counter?
A dictionary subclass from the collections module that counts how many times each value appears – perfect for quick frequency tables.
Can a list hold mixed types?
Yes, but in data work keep one type per list (like one type per column) to avoid errors in calculations.
← Data Science (60 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDay 6: Files, CSV, JSON, Errors & Modules Your progress: 5 / 60 (8%) · Lesson 6 / 60 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free