PART 2 โ€ข LEVEL 07

๐Ÿงบ Lists, Tuples & Sets

Store multiple values, update ordered data, protect fixed records and perform fast uniqueness and membership operations.

โฑ 100โ€“115 minutes๐Ÿ“š 8 concepts๐Ÿ’ป 5 programs๐Ÿง  6-question quiz
student_skills.pyPython 3
skills = ["Python", "SQL"]
skills.append("Git")
profile = ("Bhavya", 92)
unique_skills = set(skills)

print(f"Skills: {skills}")
print(f"Profile: {profile}")
print(f"Unique: {len(unique_skills)}")
OUTPUTSkills: ['Python', 'SQL', 'Git']
Profile: ('Bhavya', 92)
Unique: 3

By the End of This Level

You will be able to select and use Python collections confidently.

01

Create, access, slice and update lists.

02

Use list methods for practical data processing.

03

Store fixed records with tuples and unpack their values.

04

Use sets for uniqueness, membership and mathematical operations.

01

List Fundamentals

A list is an ordered, mutable collection written inside square brackets. It can hold values of the same or different types.

Lists preserve insertion order and allow duplicate values. Because lists are mutable, you can replace, add or remove elements after creation.

Mutable

The same list object can be changed in place without creating a completely new collection.

Empty list[]
Numbers[10, 20, 30]
Mixed values["Python", 3, True]
Lengthlen([4, 8, 12]) โ†’ 3
Reference behaviour

If second = first, both names refer to the same list. Use second = first.copy() when you need an independent shallow copy.

02

List Indexing, Slicing and Updating

Lists use the same zero-based indexing and half-open slicing rules as strings, but individual elements can be replaced.

1Locate ListSelect collection
โ†’
2Choose IndexZero-based position
โ†’
3Assign ValueReplace element
โ†’
4Use ResultUpdated list
ExpressionMeaningResult for [10, 20, 30, 40]
values[0]First element10
values[-1]Last element40
values[1:3]Indexes 1 and 2[20, 30]
values[::2]Every second element[10, 30]
values[1] = 25Replace index 1[10, 25, 30, 40]
EXAMPLE 1

Update a Course List

courses = ["Python", "C", "Java"]
courses[1] = "SQL"
print(courses)
print(courses[0:2])
OUTPUT
['Python', 'SQL', 'Java']
['Python', 'SQL']
03

Essential List Methods

MethodPurposeImportant behaviour
append(value)Add one value at the endChanges the list in place
extend(iterable)Add several valuesAdds each incoming element
insert(index, value)Add at a positionShifts later values right
remove(value)Remove first matching valueRaises an error if absent
pop()Remove and return an elementUses the last index by default
sort()Sort the same listReturns None
reverse()Reverse the same listChanges order in place
count(value)Count matchesDoes not modify the list
EXAMPLE 2

Manage Scores

scores = [72, 91, 84]
scores.append(88)
scores.sort()
print(scores)
print("Highest =", max(scores))
OUTPUT
[72, 84, 88, 91]
Highest = 91
Method versus function

scores.sort() changes scores. sorted(scores) returns a new sorted list and leaves the original collection unchanged.

04

Tuples and Unpacking

A tuple is an ordered, immutable collection. It is ideal for values that form one fixed record.

๐Ÿ”’

Immutable

Tuple elements cannot be replaced after creation.

๐Ÿ“

Ordered

Indexes and slicing work like lists.

๐Ÿ“ฆ

Unpacking

name, score = record assigns matching values.

1๏ธโƒฃ

One Item

Write (5,); the comma creates the tuple.

EXAMPLE 3

Unpack a Student Record

student = ("Bhavya", 92, "CSE-AIML")
name, score, branch = student
print(name)
print(score)
print(branch)
OUTPUT
Bhavya
92
CSE-AIML
05

Set Fundamentals

A set is an unordered collection of unique hashable values. It is powerful for removing duplicates and testing membership.

Empty setset()
Unique values{2, 4, 6}
Remove duplicatesset([2, 2, 4])
Fast membership"Python" in skills
Empty braces warning

{} creates an empty dictionary, not an empty set. Always use set() for an empty set.

06

Set Methods and Operations

OperationMeaningOperator / method
UnionValues in either seta | b or a.union(b)
IntersectionValues common to botha & b or a.intersection(b)
DifferenceValues in the first set onlya - b or a.difference(b)
Symmetric differenceValues in exactly one seta ^ b
AddInsert one valuea.add(value)
DiscardRemove if presenta.discard(value)
EXAMPLE 4

Find Common Skills

team_a = {"Python", "SQL", "C"}
team_b = {"Python", "Java", "SQL"}
common = team_a & team_b
print(sorted(common))
OUTPUT
['Python', 'SQL']
07

List vs Tuple vs Set

Choose a collection from the behaviour your problem requires, not merely from its syntax.

FIXED

Tuple ()

Use for ordered records whose structure should stay stable.

UNIQUE

Set set()

Use for unique values, membership and group comparisons.

PropertyListTupleSet
OrderedYesYesNo guaranteed position
MutableYesNoYes
DuplicatesAllowedAllowedRemoved
IndexingYesYesNo
Typical useChanging sequenceFixed recordUnique group
08

Traversal and Useful Built-ins

A for loop can visit every value. Built-ins such as len(), sum(), min(), max() and sorted() solve common collection tasks clearly.

EXAMPLE 5

Calculate a Total

marks = [78, 85, 92]
total = 0

for mark in marks:
    total += mark

print("Total =", total)
print("Average =", total / len(marks))
OUTPUT
Total = 255
Average = 85.0

Common Collection Mistakes

Wrong Copy
second = first

This creates another reference to the same list; use first.copy() for an independent shallow copy.

One-item Tuple
(5)

This is an integer inside parentheses. Write (5,) to create a tuple.

Empty Set
{}

Empty braces create a dictionary. Use set().

Method Result
scores = scores.sort()

sort() changes the list and returns None; call scores.sort() separately.

Debug collections:1. Confirm the collection type2. Check length3. Inspect indexes4. Verify mutation5. Sort sets only for predictable display
QUICK REVISION

๐Ÿ“Œ Lists, Tuples & Sets โ€” Quick Revision

Review these rules before attempting the quiz and programming problems.

01

Lists are ordered, mutable and allow duplicates.

02

List indexing starts at zero and supports negative indexes.

03

List slices exclude the stop index.

04

append() adds one value at the end.

05

sort() changes a list; sorted() returns a new list.

06

Tuples are ordered but immutable.

07

A one-item tuple requires a trailing comma.

08

Sets store unique values and do not support indexing.

09

& finds intersection and | finds union.

10

Choose a collection according to order, mutability and uniqueness.

๐Ÿง  Level 7 Quiz

Choose one answer for each question.

1. Which collection is ordered and mutable?

2. What does values.append(8) do?

3. Which expression creates a one-item tuple?

4. What does set([2, 2, 4]) contain?

5. Which operator finds common elements of two sets?

6. What does list.sort() return?

PRACTICE

๐ŸŽฏ 5 Programming Problems โ€” Lists-Tuples-Sets

Follow the CodeBhavya pattern: understand the task, inspect the sample, use the editor, run, check, then compare with the official program.

๐Ÿ“ˆ L-T-S Practice Progress
Solved0 / 5
Completed with Solution0
Total Score0 / 500
Completion0%

A problem counts as Solved when its output passes before the official solution is opened.

1. Add a New Course

Begin with Python and C, read one more course, append it and display the updated list.

Sample input: JavaExpected output: Courses = ['Python', 'C', 'Java']
2. Marks Summary

Read three marks into a list and display their total and highest value.

Sample input: 78, 85, 92Expected output: Total = 255 and Highest = 92
3. Unpack a Student Record

Read a student name and score, store them in a tuple and unpack the record.

Sample input: Bhavya, 92Expected output: Name = Bhavya and Score = 92
4. Remove Duplicate Numbers

Convert a list containing duplicates to a set and display the unique values in sorted order.

Given values: [2, 4, 2, 6, 4]Expected output: Unique = [2, 4, 6]
5. Find Common Skills

Find the skills shared by two teams and display them alphabetically.

Team A: {"Python", "SQL", "C"}Team B: {"Python", "Java", "SQL"}Expected output: Common = ['Python', 'SQL']
KEY TAKEAWAY

๐ŸŽฏ Match the Collection to the Problem

1Need Order?

Choose a sequence when position matters.

โ†’
2Need Changes?

Choose a list for mutable data.

โ†’
3Need Stability?

Choose a tuple for fixed records.

โ†’
4Need Uniqueness?

Choose a set for distinct values.

Good Python solutions begin with the right data structure: list for change, tuple for stability and set for uniqueness and group operations.

INTERACTIVE LEARNING

๐ŸŽฌ List Mutation โ€” Visual Flow

Watch one list change through append, indexed assignment and removal operations.

PROGRAM TRACING

๐Ÿ”Ž Program Tracing โ€” List Total

Move through a loop and observe how each list value changes the running total.

INTERVIEW PREPARATION

๐ŸŽค Collections โ€” Interview Questions

Answer aloud before opening each explanation.

1.

What is the main difference between a list and a tuple?

2.

Why does list.sort() return None?

3.

What is the difference between append() and extend()?

4.

Why can a set not be indexed?

5.

What is tuple unpacking?

6.

What is the average time complexity of set membership?

EXTRA TIPS

๐Ÿ’ก Collections โ€” Extra Tips

  • 01

    Use enumerate() when a loop needs both an index and a value.

  • 02

    Use copy() before changing a list that must not affect the original.

  • 03

    Prefer discard() when removing a set value that may be absent.

  • 04

    Sort a set only when display order or testing must be predictable.

  • 05

    Use tuple unpacking to make fixed records easier to read.

  • 06

    A set can contain immutable values such as numbers, strings and tuples, but not lists.

EXTRA PRACTICE

โœ๏ธ Collections โ€” Extra Practice Questions

  1. Find the second-largest distinct value in a list.
  2. Rotate a list one position to the right.
  3. Separate even and odd numbers into two lists.
  4. Merge two lists without keeping duplicate values.
  5. Count how many times a target value appears in a tuple.
  6. Swap two variables using tuple unpacking.
  7. Find the union, intersection and differences of two sets.
  8. Check whether one set is a subset of another.
  9. Find values that occur in exactly one of two lists.
  10. Remove duplicates while preserving the original list order.

Lists, Tuples & Sets Complete

When you can select the correct collection, trace list mutations, unpack tuples and solve all five set/list programs without help, mark this level complete and continue.