LearningPython TutorialTuples & Sets
CHAPTER 10 · DATA STRUCTURES

Python Tuples & Sets

Tuples aur sets dono collections hain, but unka purpose alag hai. Tuple ordered aur immutable sequence hota hai; set unique values ka unordered collection hota hai. Is chapter me dono ko practical examples ke saath compare karenge.

English + Hinglish60 min readOnline practice included

What is a tuple?

A tuple is an ordered, immutable sequence. Order preserve hota hai, duplicates allowed hote hain, but tuple ke individual items ko direct update nahi kar sakte.

tuple-basic.pyPython
point = (10, 20)
print(point)
print(type(point))
Hinglish Explanation

Tuple ko list ki tarah sequence samjho, lekin banne ke baad uski structure normally change nahi karte. Coordinates, fixed settings, database-like records ya multiple return values me tuples useful hote hain.

Try a tuple →

Create tuples

create-tuples.pyPython
empty = ()
colors = ("navy", "blue", "white")
numbers = (10, 20, 30, 20)
mixed = (1, "Python", True, 3.5)

print(colors)
print(numbers)

Parentheses common hain, lekin technically comma tuple banane me key role play karta hai.

Single-item tuple

Single value ke tuple me trailing comma zaroori hai.

single.pyPython
not_tuple = (5)
one_item = (5,)

print(type(not_tuple))
print(type(one_item))
Important: (5) sirf integer expression hai. (5,) tuple hai.

Tuple indexing and slicing

Tuple ordered sequence hai, isliye indexing aur slicing lists aur strings jaisi hoti hai.

tuple-index.pyPython
languages = ("HTML", "CSS", "JavaScript", "Python")

print(languages[0])
print(languages[-1])
print(languages[1:3])
print(languages[::-1])

Tuple immutability

Tuple ke element references ko direct replace nahi kar sakte.

immutable.pyPython
point = (10, 20)
# point[0] = 99  # TypeError

Immutability accidental structural changes ko reduce karti hai.

Nuance: Agar tuple ke andar mutable object ho, jaise list, to us inner object ko mutate kiya ja sakta hai. Tuple khud immutable hai, har nested object automatically immutable nahi hota.
nested-mutable.pyPython
record = ("Aman", [80, 90])
record[1].append(95)
print(record)

Tuple methods

Tuple intentionally small method API rakhta hai.

tuple-methods.pyPython
scores = (70, 80, 90, 80)

print(scores.count(80))
print(scores.index(90))
  • count(value) — occurrences count karta hai.
  • index(value) — first matching index return karta hai.

Tuple packing and unpacking

Multiple values ko tuple me pack aur variables me unpack kar sakte ho.

packing.pyPython
student = "Aman", 21, "Python"
name, age, course = student

print(name)
print(age)
print(course)

Try unpacking →

Extended unpacking

extended.pyPython
values = (10, 20, 30, 40, 50)
first, *middle, last = values

print(first)
print(middle)
print(last)

Starred variable remaining values ko list me collect karta hai.

Tuple operations

tuple-ops.pyPython
a = (1, 2)
b = (3, 4)

print(a + b)
print(a * 2)
print(2 in a)
print(len(a))

Concatenation aur repetition new tuples create karte hain; original tuple mutate nahi hota.

When should you use a tuple?

  • Fixed-position data, jaise coordinates (x, y).
  • Function se multiple values return karna.
  • Read-only style records jahan accidental edits avoid karne hain.
  • Dictionary key ya set element ke roop me immutable values represent karna, jab contained items bhi hashable hon.
Rule of thumb: Data ko frequently add/remove/update karna hai to list usually better. Fixed sequence semantics chahiye to tuple clearer ho sakta hai.

What is a set?

A set is a mutable collection of unique hashable elements. Sets membership tests, duplicate removal aur mathematical set operations ke liye useful hote hain.

set-basic.pyPython
skills = {"HTML", "CSS", "Python"}
print(skills)
print(type(skills))
Hinglish Explanation

Set me duplicate values automatically collapse ho jati hain. Set ko index se access nahi karte because it is not a sequence with positional indexing.

Create sets correctly

create-sets.pyPython
numbers = {1, 2, 3, 3, 2}
empty_set = set()
empty_dict = {}

print(numbers)
print(type(empty_set))
print(type(empty_dict))
Important: {} empty dictionary banata hai, empty set nahi. Empty set ke liye set() use karo.

Remove duplicates with a set

unique.pyPython
tags = ["python", "css", "python", "html", "css"]
unique_tags = set(tags)

print(unique_tags)

Set duplicate removal easy banata hai, but original order ko preserve karne ki requirement ho to set conversion blindly use mat karo.

Try duplicate removal →

Fast membership checks

membership.pyPython
allowed_roles = {"admin", "editor", "author"}
role = "editor"

if role in allowed_roles:
    print("Allowed")

Membership-heavy workflows me set often list se better intent express karta hai.

Add and remove set items

set-update.pyPython
skills = {"HTML", "CSS"}
skills.add("Python")
skills.update(["JavaScript", "Git"])

skills.discard("CSS")
print(skills)
  • add(value) — one item add karta hai.
  • update(iterable) — multiple items add karta hai.
  • remove(value) — missing item par KeyError.
  • discard(value) — missing item par error nahi.
  • pop() — arbitrary item remove/return karta hai; list ke last-item pop jaisa assume mat karo.
  • clear() — all items remove karta hai.

Union, intersection and difference

operations.pyPython
frontend = {"HTML", "CSS", "JavaScript"}
backend = {"Python", "JavaScript", "SQL"}

print(frontend | backend)   # union
print(frontend & backend)   # intersection
print(frontend - backend)   # difference
print(frontend ^ backend)   # symmetric difference

Run set operations →

Method forms of set operations

set-methods.pyPython
a = {1, 2, 3}
b = {3, 4, 5}

print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(a.symmetric_difference(b))

Operator aur method forms dono valid hain. Team/codebase style ke hisab se readable form choose karo.

Subset, superset and disjoint checks

relations.pyPython
required = {"html", "css"}
student = {"html", "css", "javascript"}

print(required <= student)
print(student >= required)
print(required.isdisjoint({"python", "sql"}))
  • <= / issubset() — all left items right side me hain?
  • >= / issuperset() — right side ke all items left me hain?
  • isdisjoint() — koi common item nahi?

What can a set contain?

Set elements hashable hone chahiye. Numbers, strings aur suitable tuples set me ho sakte hain; normal lists aur dictionaries directly set elements nahi ban sakte.

hashable.pyPython
valid = {1, "python", (10, 20)}
print(valid)

# invalid = {[1, 2]}  # TypeError: list is unhashable

frozenset preview

frozenset immutable set variant hai.

frozenset.pyPython
permissions = frozenset({"read", "write"})
print(permissions)
# permissions.add("delete")  # AttributeError

Jab set semantics chahiye but mutation allow nahi karni, frozenset useful ho sakta hai.

Tuple vs set vs list

  • List: ordered, mutable, duplicates allowed.
  • Tuple: ordered, immutable, duplicates allowed.
  • Set: unique elements, mutable collection, no positional indexing.
Choose by meaning: “ordered editable sequence” → list, “fixed sequence” → tuple, “unique membership/group math” → set.

Practical workflow — skills comparison

skills.pyPython
required_skills = {"python", "sql", "git"}
student_skills = set(input("Skills comma-separated: ").lower().split(","))
student_skills = {skill.strip() for skill in student_skills if skill.strip()}

missing = required_skills - student_skills
matched = required_skills & student_skills

print("Matched:", matched)
print("Missing:", missing)

if required_skills <= student_skills:
    print("Core skill requirement met")
else:
    print("Keep learning")
Preview: Set comprehension syntax Chapter 19 me detail me cover hoga. Yahan practical flow samajhne ke liye use hua hai.

Run skills comparison →

Common beginner mistakes

  • Single-item tuple me comma bhoolna.
  • Tuple item ko list ki tarah direct assign/update karna.
  • Tuple ke andar mutable object hone par “everything is immutable” assume karna.
  • {} ko empty set samajhna.
  • Set ko indexing se access karne ki koshish karna.
  • Set output order par application logic depend karna.
  • remove() aur discard() ka behavior confuse karna.
  • pop() ko “last item” remove karne wala method samajhna.
  • Lists/dicts ko direct set elements banana.
  • Duplicate removal ke liye set use karke required order lose kar dena.
  • List, tuple aur set ko syntax ke basis par choose karna instead of data meaning.

Beginner best practices

  • Fixed ordered data ke liye tuple consider karo.
  • Unique membership data ke liye set consider karo.
  • Empty set ke liye always set() use karo.
  • Missing value expected ho sakti hai to discard() safer ho sakta hai.
  • Set order ko meaningful sequence mat samjho.
  • Set operations ko intent express karne ke liye use karo instead of complicated loops.
  • Tuple unpacking tab use karo jab positions ka meaning clear ho.
  • Data structure choose karte waqt mutability, order, uniqueness aur lookup intent socho.

Chapter checklist

  • Tuple create, index and slice kar sakte ho?
  • Single-item tuple ka comma rule clear hai?
  • Tuple immutability aur nested mutable nuance samajh aaya?
  • Tuple packing/unpacking kar sakte ho?
  • Empty set correctly create kar sakte ho?
  • Set me add/remove/discard use kar sakte ho?
  • Union, intersection, difference aur symmetric difference samajh aaye?
  • Subset/superset membership relations check kar sakte ho?
  • List vs tuple vs set ka correct use-case choose kar sakte ho?

Practice Task — Course Skills Analyzer

BrounStack Playground me tuple + set based learner skills analyzer banao.

  1. Student basic profile ko tuple me store karo: name, city, course.
  2. Tuple unpack karke values print karo.
  3. Required skills ko set me store karo.
  4. Student ke learned skills ko another set me store karo.
  5. Duplicate skill input test karo aur observe karo.
  6. Matched skills intersection se nikaalo.
  7. Missing skills difference se nikaalo.
  8. All known skills union se nikaalo.
  9. Required set subset hai ya nahi check karo.
  10. One irrelevant-skills set ke saath isdisjoint() test karo.
  11. add() se ek new skill add karo.
  12. discard() se ek skill safely remove karo.
  13. List, tuple aur set ke final values print karo.
  14. Explain karo ki profile ke liye tuple aur skills ke liye set kyon useful the.

Open practice starter →