0% found this document useful (0 votes)
2 views60 pages

Python Unit 3 Notes

This document provides an overview of data structures in Python, focusing on lists, tuples, and dictionaries. It explains the characteristics, creation, manipulation, and common operations associated with each data structure, including methods and examples. Additionally, it highlights common mistakes and practice problems to reinforce learning.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views60 pages

Python Unit 3 Notes

This document provides an overview of data structures in Python, focusing on lists, tuples, and dictionaries. It explains the characteristics, creation, manipulation, and common operations associated with each data structure, including methods and examples. Additionally, it highlights common mistakes and practice problems to reinforce learning.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT III – DATA STRUCTURES IN PYTHON

Part 1: LISTS IN PYTHON

1. Introduction to Lists
A list in Python is:

• An ordered collection of elements


• Mutable (can be modified)
• Can store different data types
• Can grow or shrink dynamically

In simple words:

A list stores multiple values inside a single variable.

Real-Life Analogy
A list is like:

• A list of students in a classroom


• Items in a shopping cart
• Marks of students

2. Creating a List
Lists are created using square brackets [].

Example
numbers = [10, 20, 30, 40]
print(numbers)

Output

[10, 20, 30, 40]


List with Mixed Data Types
data = [10, "Python", 3.5, True]
print(data)

3. Accessing List Elements


Lists use indexing, starting from 0.

Example
fruits = ["Apple", "Mango", "Orange"]
print(fruits[0])
print(fruits[2])

Output

Apple
Orange

Negative Indexing
print(fruits[-1])

Output:

Orange

4. Updating List Elements


Lists are mutable, so values can be changed.

Example
numbers = [10, 20, 30]
numbers[1] = 50
print(numbers)

Output

[10, 50, 30]


5. Nested Lists
A list can contain another list.

Example
matrix = [[1, 2], [3, 4]]
print(matrix[0])
print(matrix[1][1])

Output

[1, 2]
4

6. List Operations

6.1 Concatenation (+)


a = [1, 2]
b = [3, 4]
print(a + b)

Output:

[1, 2, 3, 4]

6.2 Repetition (*)


print([1, 2] * 3)

Output:

[1, 2, 1, 2, 1, 2]

6.3 Membership Operator


print(2 in [1, 2, 3])

Output:
True

7. Important List Methods

append() – Add element at end


numbers = [1, 2]
[Link](3)
print(numbers)

Output:

[1, 2, 3]

insert() – Add at specific position


[Link](1, 10)
print(numbers)

remove() – Remove value


[Link](10)
print(numbers)

pop() – Remove using index


[Link]()

sort() – Sort list


[Link]()

reverse()
[Link]()
8. Cloning Lists (Important Concept)
Problem: Assignment copies reference
a = [1, 2, 3]
b = a
b[0] = 100
print(a)

Output:

[100, 2, 3]

Both change!

Correct Cloning
b = [Link]()

or

b = a[:]

9. Using Loops with Lists


Example
numbers = [1, 2, 3]

for n in numbers:
print(n)

Using Index
for i in range(len(numbers)):
print(numbers[i])
10. List as Stack (LIFO)
Stack: Last In First Out.

Example
stack = []
[Link](10)
[Link](20)
[Link](30)

print([Link]())

Output:

30

11. List as Queue (FIFO)


Queue: First In First Out.

Example
queue = []
[Link](10)
[Link](20)
[Link](30)

print([Link](0))

Output:

10

12. Common Beginner Mistakes


Index Out of Range
a = [1,2]
print(a[5])

Error occurs.
Removing Non-Existing Element
[Link](10)

Error if value absent.

13. Practice Problems


1. Read 5 numbers into a list and print maximum.
2. Reverse a list without built-in reverse.
3. Count even numbers in a list.
4. Implement stack operations.
5. Merge two lists and sort.

14. Unit III Learning Checkpoint


After mastering lists, students should:

• Store sequences of data


• Modify stored values
• Traverse data efficiently
• Use lists in algorithmic tasks

List Methods — Examples with Output

1. insert() – Add Element at Specific Position


Purpose: Inserts an element at a given index.

Example
numbers = [1, 2, 3, 4]

[Link](1, 10)
print(numbers)

Output
[1, 10, 2, 3, 4]
Explanation
• Element 10 inserted at index 1
• Existing elements shift right

2. remove() – Remove Specific Value


Purpose: Removes the first occurrence of a value.

Example
numbers = [1, 10, 2, 3, 4]

[Link](10)
print(numbers)

Output
[1, 2, 3, 4]

Explanation
• Removes value 10
• First matching value removed

3. pop() – Remove Element Using Index


Purpose: Removes element at a given index. If no index is provided, last element is removed.

Example
numbers = [1, 2, 3, 4]

[Link]()
print(numbers)

Output
[1, 2, 3]

Example with Index


numbers = [1, 2, 3, 4]

[Link](1)
print(numbers)
Output
[1, 3, 4]

Explanation
Element at index 1 removed.

4. sort() – Sort List


Purpose: Sorts list in ascending order.

Example
numbers = [4, 1, 3, 2]

[Link]()
print(numbers)

Output
[1, 2, 3, 4]

Descending Order
[Link](reverse=True)
print(numbers)

Output:

[4, 3, 2, 1]

5. reverse() – Reverse List Order


Purpose: Reverses the list order.

Example
numbers = [1, 2, 3, 4]

[Link]()
print(numbers)
Output
[4, 3, 2, 1]

Summary Table
Method Example Result
insert() Adds element at position
remove() Removes by value
pop() Removes by index
sort() Sorts list
reverse() Reverses list

Important distinction:

✅ Some are list methods (called using [Link]()), ✅ Others are built-in functions (called
using function(list)).

Students often confuse these, so this table helps clearly.

✅ Functions That Work With Lists (Built-in


Functions)
These are Python built-in functions, not list methods.

1. len() – Length of List


numbers = [10, 20, 30]
print(len(numbers))

Output:

2. sum() – Sum of Elements


numbers = [10, 20, 30]
print(sum(numbers))
Output:

60

Works only for numeric lists.

3. max() – Largest Element


numbers = [5, 8, 2]
print(max(numbers))

Output:

4. min() – Smallest Element


numbers = [5, 8, 2]
print(min(numbers))

Output:

5. sorted() – Returns Sorted Copy


numbers = [4, 1, 3]
print(sorted(numbers))

Output:

[1, 3, 4]

Original list remains unchanged.

6. reversed() – Reverse Iterator


numbers = [1, 2, 3]
print(list(reversed(numbers)))

Output:
[3, 2, 1]

7. list() – Convert to List


text = "ABC"
print(list(text))

Output:

['A', 'B', 'C']

8. any() – True if Any Element is True


values = [0, False, 5]
print(any(values))

Output:

True

9. all() – True if All Elements True


values = [1, True, 3]
print(all(values))

Output:

True

✅ List Methods (Operate Directly on List)


These are called using [Link]().

1. append()
Adds element at end.
a = [1,2]
[Link](3)

2. insert()
Insert at index.

[Link](1, 10)

3. remove()
Remove by value.

[Link](10)

4. pop()
Remove by index.

[Link]()
[Link](1)

5. clear()
Remove all elements.

[Link]()

6. index()
Find element index.

[Link](3)
7. count()
Count occurrences.

[Link](2)

8. sort()
Sort list permanently.

[Link]()

9. reverse()
Reverse permanently.

[Link]()

10. copy()
Clone list.

b = [Link]()

✅ Operators That Work With Lists

Concatenation
a + b

Repetition
a * 3
Membership
2 in a

Indexing
a[0]

Slicing
a[1:4]

✅ Quick Summary Table


Built-in Functions
len(), sum(), max(), min(), sorted(),
reversed(), list(), any(), all()

List Methods
append(), insert(), remove(), pop(),
clear(), index(), count(),
sort(), reverse(), copy()

Students should remember:

Functions use: function(list)


Methods use: [Link]()

Example:

sum(list) ✔
[Link]() ✖
UNIT III – TUPLES IN PYTHON
Tuples are an important structure used when data should not change after creation. They are
widely used in real systems for fixed records, coordinates, database rows, and returning
multiple values from functions.

1. Introduction to Tuples
A tuple is:

• An ordered collection of elements


• Immutable (cannot be modified after creation)
• Allows mixed data types
• Indexed like lists

In simple terms:

A tuple is like a list whose values cannot be changed.

Real-Life Example
Examples where data should not change:

• Date of birth
• GPS coordinates
• Student record ID
• Bank transaction record

Such fixed data is stored using tuples.

2. Creating Tuples
Tuples are created using parentheses ().

Example
numbers = (10, 20, 30)
print(numbers)

Output:

(10, 20, 30)


Tuple with Mixed Data
data = (10, "Python", 3.5)
print(data)

Tuple Without Parentheses


Parentheses are optional.

t = 1, 2, 3
print(t)

Single Element Tuple (Important)


t = (5,)
print(type(t))

Without comma:

t = (5)
print(type(t))

This becomes an integer, not a tuple.

3. Accessing Tuple Elements


Tuple indexing works like lists.

Example
t = (10, 20, 30)
print(t[0])
print(t[-1])

Output:

10
30
Tuple Slicing
print(t[1:3])

Output:

(20, 30)

4. Immutability of Tuples
Tuples cannot be modified.

Invalid Operation
t = (10, 20, 30)
t[1] = 50

Error:

TypeError

5. Updating Tuples (Reassignment Concept)


Since tuples cannot change, updating means creating a new tuple.

Example
t = (10, 20, 30)
t = (10, 50, 30)
print(t)

6. Deleting Tuples
Individual elements cannot be deleted, but entire tuple can be deleted.

t = (1, 2, 3)
del t
7. Tuple Assignment (Packing & Unpacking)
Packing
t = 10, 20, 30

Unpacking
a, b, c = t
print(a, b, c)

Output:

10 20 30

8. Returning Multiple Values from Functions


Functions return multiple values using tuples.

Example
def calc():
return 10, 20

x, y = calc()
print(x, y)

Output:

10 20

This feature is heavily used in real programs.

9. Nested Tuples
Tuples can contain other tuples.

Example
t = ((1, 2), (3, 4))
print(t[1][0])

Output:

3
10. Tuple Operations
Concatenation
a = (1, 2)
b = (3, 4)
print(a + b)

Output:

(1, 2, 3, 4)

Repetition
print((1, 2) * 2)

Output:

(1, 2, 1, 2)

Membership
print(2 in (1, 2, 3))

Output:

True

11. Tuple Methods


Tuples have only two methods.

count()
Counts occurrences.

t = (1, 2, 2, 3)
print([Link](2))

Output:
2

index()
Returns index of element.

print([Link](3))

Output:

12. Looping Through Tuples


Example
t = (10, 20, 30)
for x in t:
print(x)

13. Tuple vs List (Exam Concept)


Feature List Tuple
Mutable Yes No
Faster No Yes
Syntax [] ()
Use case Changing data Fixed data

14. Common Beginner Mistakes


Missing comma in single tuple
t = (5)

Not a tuple.
Trying to modify tuple
t[0] = 10

Error.

15. Practice Problems


1. Create a tuple storing student name, age, and marks.
2. Write a function returning sum and product of two numbers.
3. Count occurrences of an element in tuple.
4. Access element in nested tuple.
5. Unpack tuple into variables and print them.

16. Learning Outcome After Tuples


Students should now:

• Store fixed records


• Return multiple values
• Understand immutability
• Use tuple unpacking
• Traverse nested structures

1. Introduction to Dictionaries
A dictionary is:

• A collection of key–value pairs


• Unordered collection (conceptually)
• Mutable (can be modified)
• Indexed using keys instead of numbers

In simple words:

A dictionary stores data in the form key → value.

Real-Life Example
Student record:

Field Value
Name Ravi
Field Value
Age 20
Marks 85

This maps naturally as:

student = {
"name": "Ravi",
"age": 20,
"marks": 85
}

2. Creating Dictionaries
Dictionaries are created using curly braces {}.

Example
student = {"name": "John", "age": 21}
print(student)

Output:

{'name': 'John', 'age': 21}

Empty Dictionary
d = {}

3. Accessing Dictionary Values


Values are accessed using keys.

Example
student = {"name": "John", "age": 21}

print(student["name"])

Output:

John
Using get() Method (Safer Access)
print([Link]("age"))

If key not found, it returns None instead of error.

4. Adding Elements to Dictionary


New key-value pairs can be added.

Example
student["marks"] = 90
print(student)

Output:

{'name': 'John', 'age': 21, 'marks': 90}

5. Modifying Dictionary Values


Values can be updated.

student["age"] = 22

6. Deleting Elements
Using del
del student["age"]

Using pop()
[Link]("marks")
Remove Last Item
[Link]()

7. Looping Through Dictionaries

Loop Through Keys


for key in student:
print(key)

Loop Through Values


for value in [Link]():
print(value)

Loop Through Both


for k, v in [Link]():
print(k, v)

8. Nested Dictionaries
A dictionary can contain another dictionary.

Example
students = {
1: {"name": "Asha", "marks": 90},
2: {"name": "Rahul", "marks": 85}
}

print(students[1]["name"])

Output:

Asha
9. Sorting Dictionary Items
Dictionary items can be sorted using keys.

Example
marks = {"A": 90, "C": 80, "B": 85}

for k in sorted(marks):
print(k, marks[k])

Output:

A 90
B 85
C 80

10. Built-in Dictionary Methods

keys()
Returns all keys.

print([Link]())

values()
Returns all values.

print([Link]())

items()
Returns key-value pairs.

print([Link]())
update()
Updates dictionary.

[Link]({"age": 23})

clear()
Removes all elements.

[Link]()

11. String Formatting with Dictionaries


Dictionaries are often used in formatted output.

Example
student = {"name": "John", "age": 21}

print("Name: {name}, Age: {age}".format(**student))

Output:

Name: John, Age: 21

12. Membership Checking


print("name" in student)

Output:

True

13. Common Beginner Mistakes

Accessing Missing Key


print(student["salary"])
Error occurs.

Use:

[Link]("salary")

Duplicate Keys
d = {"a": 1, "a": 2}

Only last value stored.

14. Practice Problems


1. Create dictionary storing employee details.
2. Add salary to employee record.
3. Print all keys and values.
4. Count number of entries.
5. Create nested dictionary for students.

15. Learning Outcome After Dictionaries


Students should now be able to:

• Store structured data


• Model real entities
• Access and update data
• Traverse key-value mappings
• Build nested data models

Dictionary Complete Demonstration Example


Scenario: Student Record Management
We store student details in a dictionary.
Step 1: Create Dictionary
Code
student = {
"name": "Ravi",
"age": 20,
"marks": 85
}

print(student)

Output
{'name': 'Ravi', 'age': 20, 'marks': 85}

Step 2: Access Values Using Keys


Code
print(student["name"])
print(student["marks"])

Output
Ravi
85

Step 3: Access Using get()


Safer access method.

print([Link]("age"))
print([Link]("grade"))

Output
20
None
Step 4: Add New Key-Value Pair
student["grade"] = "A"
print(student)

Output
{'name': 'Ravi', 'age': 20, 'marks': 85, 'grade': 'A'}

Step 5: Modify Existing Value


student["marks"] = 90
print(student)

Output
{'name': 'Ravi', 'age': 20, 'marks': 90, 'grade': 'A'}

Step 6: keys() Method


Shows all keys.

print([Link]())

Output
dict_keys(['name', 'age', 'marks', 'grade'])

Step 7: values() Method


Shows all values.

print([Link]())

Output
dict_values(['Ravi', 20, 90, 'A'])
Step 8: items() Method
Shows key-value pairs.

print([Link]())

Output
dict_items([('name', 'Ravi'), ('age', 20), ('marks', 90), ('grade',
'A')])

Step 9: Loop Through Dictionary


Loop Keys
for key in student:
print(key)

Output:

name
age
marks
grade

Loop Values
for value in [Link]():
print(value)

Loop Both Key & Value


for k, v in [Link]():
print(k, ":", v)

Output:

name : Ravi
age : 20
marks : 90
grade : A
Step 10: update() Method
Updates dictionary with new values.

[Link]({"age": 21, "city": "Chennai"})


print(student)

Output
{'name': 'Ravi', 'age': 21, 'marks': 90, 'grade': 'A', 'city':
'Chennai'}

Step 11: pop() Method


Removes specific key.

[Link]("city")
print(student)

Output
{'name': 'Ravi', 'age': 21, 'marks': 90, 'grade': 'A'}

Step 12: popitem() Method


Removes last inserted item.

[Link]()
print(student)

Output
{'name': 'Ravi', 'age': 21, 'marks': 90}

(grade removed)

Step 13: del Keyword


del student["age"]
print(student)
Output
{'name': 'Ravi', 'marks': 90}

Step 14: Membership Test


print("name" in student)
print("age" in student)

Output
True
False

Step 15: Sorting Dictionary Keys


for key in sorted(student):
print(key, student[key])

Output
marks 90
name Ravi

Step 16: clear() Method


Remove all elements.

[Link]()
print(student)

Output
{}

Final Operations Covered


This example demonstrated:
Operation Covered
Create dictionary ✔
Access values ✔
get() ✔
Add elements ✔
Modify values ✔
keys() ✔
values() ✔
items() ✔
Loop dictionary ✔
update() ✔
pop() ✔
popitem() ✔
del ✔
Membership test ✔
Sorting keys ✔
clear() ✔

Learning Outcome
• Dictionary structure
• CRUD operations
• Looping and updates
• Safe access patterns
• Removal operations
• Dictionary traversal

Real-Time Dictionary Problems with Answers

✅ Problem 1: Student Result Management System


Problem Statement
A school stores student marks using roll numbers as keys.

Write a program to:

1. Store marks of 3 students in a dictionary.


2. Accept a roll number from the user.
3. Display marks if student exists.
4. Otherwise display "Student not found".

Model Answer
students = {
101: 85,
102: 90,
103: 78
}

roll = int(input("Enter roll number: "))

if roll in students:
print("Marks:", students[roll])
else:
print("Student not found")

Example Output
Enter roll number: 102
Marks: 90

✅ Problem 2: Online Store Inventory Tracker


Problem Statement
An online store tracks product stock using a dictionary.

Write a program to:

1. Store products and quantities.


2. Update stock when items are sold.
3. Display updated inventory.

Model Answer
inventory = {
"Laptop": 10,
"Mobile": 20,
"Tablet": 15
}
product = input("Enter product sold: ")
qty = int(input("Enter quantity sold: "))

if product in inventory:
inventory[product] -= qty

print("Updated Inventory:", inventory)

Example Output
Enter product sold: Laptop
Enter quantity sold: 2
Updated Inventory: {'Laptop': 8, 'Mobile': 20, 'Tablet': 15}

✅ Problem 3: Employee Salary Lookup


Problem Statement
A company stores employee salaries.

Write a program to:

1. Store employee names and salaries.


2. Display employees earning above 50,000.

Model Answer
employees = {
"Ravi": 45000,
"Meena": 60000,
"John": 55000
}

for name, salary in [Link]():


if salary > 50000:
print(name, "earns", salary)

Output
Meena earns 60000
John earns 55000
✅ Problem 4: Voting System Counter
Problem Statement
Votes are counted using candidate names as keys.

Write a program to:

1. Record votes.
2. Display vote count for each candidate.

Model Answer
votes = {}

for i in range(5):
candidate = input("Enter vote: ")

if candidate in votes:
votes[candidate] += 1
else:
votes[candidate] = 1

print("Vote Count:", votes)

Example Output
Vote Count: {'A': 3, 'B': 2}

✅ Problem 5: Product Price Finder


Problem Statement
A store maintains product prices.

Write a program to:

1. Store product-price dictionary.


2. Find total cost of purchased items.

Model Answer
prices = {
"Pen": 10,
"Book": 50,
"Bag": 500
}

item = input("Enter product: ")


qty = int(input("Enter quantity: "))

if item in prices:
total = prices[item] * qty
print("Total price:", total)
else:
print("Product not found")

Example Output
Enter product: Book
Enter quantity: 2
Total price: 100

Skills Practiced
Students learn:

✔ Dictionary creation ✔ Accessing data ✔ Updating values ✔ Looping through items ✔


Membership checking ✔ Real-time data modeling

UNIT III – SETS IN PYTHON


Sets are extremely useful when working with unique data and when performing mathematical
set operations such as union and intersection.

After lists (sequences), tuples (fixed records), and dictionaries (key-value mappings), sets help
manage collections where duplication is not allowed.

1. Introduction to Sets
A set in Python is:

• An unordered collection
• Mutable (elements can be added or removed)
• Contains unique elements only
• Does not allow duplicates
• Does not support indexing

In simple words:

A set stores values without repetition.

Real-Life Example
Examples where uniqueness matters:

• Unique student IDs


• Unique usernames
• Unique subjects chosen
• Unique product codes

2. Creating Sets
Sets are created using curly braces {} or the set() function.

Example
numbers = {1, 2, 3, 4}
print(numbers)

Output:

{1, 2, 3, 4}

Duplicate Values Automatically Removed


data = {1, 2, 2, 3}
print(data)

Output:

{1, 2, 3}

Creating Empty Set (Important)


s = set()
Using {} creates a dictionary, not a set.

3. Accessing Set Elements


Sets do not support indexing.

s = {10, 20, 30}


print(s[0]) # Error

Instead, use loops.

for x in s:
print(x)

4. Adding Elements to Set


add() – Add single element
s = {1, 2}
[Link](3)
print(s)

update() – Add multiple elements


[Link]([4, 5])

5. Removing Elements
remove()
Raises error if element absent.

[Link](2)

discard()
Does not raise error.
[Link](10)

pop()
Removes random element.

[Link]()

clear()
Removes all elements.

[Link]()

6. Set Operations (Very Important)


Python supports mathematical set operations.

6.1 Union (All elements)


A = {1, 2, 3}
B = {3, 4, 5}

print(A | B)

Output:

{1, 2, 3, 4, 5}

6.2 Intersection (Common elements)


print(A & B)

Output:

{3}
6.3 Difference
print(A - B)

Output:

{1, 2}

6.4 Symmetric Difference


print(A ^ B)

Output:

{1, 2, 4, 5}

7. Membership Checking
print(3 in A)

Output:

True

8. Built-in Set Methods


Method Purpose
add() Add element
update() Add many elements
remove() Remove element
discard() Remove safely
pop() Remove random element
clear() Remove all
union() Combine sets
intersection() Common elements
9. Looping Through Sets
s = {10, 20, 30}

for x in s:
print(x)

Order may vary because sets are unordered.

10. Practical Example – Unique Subjects


subjects = {"Math", "Physics", "Math", "Chemistry"}
print(subjects)

Output:

{'Math', 'Physics', 'Chemistry'}

Duplicates automatically removed.

11. Common Beginner Mistakes


Mistake 1: Using index
s[0]

Not allowed.

Mistake 2: Using list inside set


s = {[1,2]}

Error because lists are mutable.

12. Practice Problems


1. Create a set of subjects and print unique ones.
2. Add new elements into a set.
3. Find union of two sets.
4. Find common elements between sets.
5. Remove elements safely.
13. Learning Outcome After Sets
Should now:

• Handle unique data collections


• Perform set mathematics
• Eliminate duplicates
• Apply membership testing

Structure Purpose
Lists Ordered sequences
Tuples Fixed records
Dictionaries Key-value mapping
Sets Unique collections

Practical Skill Outcome After Unit III


Can now model:

• Student records
• Shopping carts
• Employee databases
• Unique membership lists
• Inventory systems

Practice Problems – Lists and Tuples

Problem 1: Online Shopping Cart Manager (Lists)


An online shopping application stores items added to a cart.

Write a program to:

1. Read N product prices into a list.


2. Display total cart value.
3. Remove an item using its index.
4. Display updated cart value.
Problem 2: Student Marks Analyzer (Lists + Loops)
A teacher enters marks of students in a class.

Write a program to:

1. Store marks of students in a list.


2. Count number of students scoring above 75.
3. Find highest and lowest marks.
4. Display average marks.

Problem 3: Employee Salary Update System (List Update)


A company stores employee salaries in a list.

Write a program to:

1. Increase salaries by 10%.


2. Replace salaries below 20,000 with 20,000.
3. Print updated salary list.

Problem 4: Matrix Row Sum Calculator (Nested Lists)


A matrix stores daily sales data for branches.

Write a program to:

1. Accept a 2×3 sales matrix.


2. Print total sales of each row.
3. Display overall total sales.

Problem 5: Stack Simulation – Browser History (Lists as


Stack)
A browser stores page visits in stack form.

Write a program to:

1. Push visited pages into stack.


2. Pop the last visited page when user presses back.
3. Display current history.
Problem 6: Queue Simulation – Customer Service (Lists as
Queue)
A bank queue system stores customers in arrival order.

Write a program to:

1. Add customers to queue.


2. Serve (remove) customers in order.
3. Display remaining queue.

Problem 7: Product Price Comparison (List Operations)


Two stores provide price lists.

Write a program to:

1. Combine price lists of two stores.


2. Sort prices.
3. Display top 3 cheapest products.

Problem 8: Tuple-based Student Record


Each student record contains: (name, roll number, marks)

Write a program to:

1. Store records using tuples.


2. Print details of students scoring above 80.
3. Count total students.

Problem 9: Function Returning Multiple Values (Tuple


Return)
Write a function that:

1. Accepts a list of numbers.


2. Returns maximum and minimum values as tuple.
3. Display returned values.

Problem 10: GPS Coordinate Analyzer (Nested Tuple)


GPS coordinates are stored as tuples: (latitude, longitude)
Write a program to:

1. Store coordinates of 3 locations.


2. Print all coordinates.
3. Display first location details.

Problem 11: Duplicate Removal Using List Logic


A system records product IDs with duplicates.

Write a program to:

1. Store IDs in a list.


2. Remove duplicates manually using loops.
3. Print unique IDs.

(Set not allowed yet.)

Problem 12: List Cloning Demonstration


Write a program to:

1. Create a list of numbers.


2. Clone the list correctly.
3. Modify cloned list.
4. Show original list remains unchanged.

Problem 13: Sales Data Processing


Daily sales amounts are stored in a list.

Write a program to:

1. Print days with sales above average.


2. Count total such days.

Problem 14: Tuple Packing and Unpacking


Write a program that:

1. Stores student name, department, and CGPA in a tuple.


2. Unpack values into variables.
3. Print them separately.
Problem 15: List Rotation Program
Write a program to:

1. Rotate list elements to the right by one position.


2. Example: [1,2,3,4] → [4,1,2,3].

Skills Covered
Skill Covered
List creation & access ✔
List update operations ✔
Nested lists ✔
Loops with lists ✔
Stack usage ✔
Queue usage ✔
List cloning ✔
Tuple creation ✔
Tuple unpacking ✔
Tuple return values ✔
Nested tuples ✔

Model Answers – Lists and Tuples Practice


Problems

✅ Problem 1 – Online Shopping Cart Manager


n = int(input("Enter number of products: "))
cart = []

for _ in range(n):
price = float(input("Enter product price: "))
[Link](price)

print("Total cart value:", sum(cart))

index = int(input("Enter index to remove: "))


[Link](index)
print("Updated cart:", cart)
print("Updated total:", sum(cart))

✅ Problem 2 – Student Marks Analyzer


marks = []
n = int(input("Enter number of students: "))

for _ in range(n):
[Link](int(input("Enter marks: ")))

count = 0
for m in marks:
if m > 75:
count += 1

print("Students above 75:", count)


print("Highest marks:", max(marks))
print("Lowest marks:", min(marks))
print("Average:", sum(marks) / len(marks))

✅ Problem 3 – Employee Salary Update


salaries = [18000, 25000, 30000, 15000]

for i in range(len(salaries)):
salaries[i] *= 1.10
if salaries[i] < 20000:
salaries[i] = 20000

print("Updated salaries:", salaries)

✅ Problem 4 – Matrix Row Sum


matrix = []

for i in range(2):
row = []
for j in range(3):
[Link](int(input("Enter value: ")))
[Link](row)

total = 0
for row in matrix:
print("Row sum:", sum(row))
total += sum(row)

print("Overall total:", total)

✅ Problem 5 – Browser History Stack


stack = []

[Link]("Google")
[Link]("YouTube")
[Link]("ChatGPT")

print("History:", stack)

[Link]()
print("After back:", stack)

✅ Problem 6 – Bank Queue Simulation


queue = ["A", "B", "C"]

print("Queue:", queue)

[Link](0)
print("After serving:", queue)

✅ Problem 7 – Product Price Comparison


store1 = [100, 200, 150]
store2 = [120, 180, 160]

combined = store1 + store2


[Link]()

print("Top 3 cheapest:", combined[:3])


✅ Problem 8 – Tuple Student Record
records = [
("Asha", 1, 85),
("Ravi", 2, 70),
("John", 3, 90)
]

count = 0
for name, roll, marks in records:
if marks > 80:
print(name, roll, marks)
count += 1

print("Total students:", count)

✅ Problem 9 – Function Returning Multiple Values


def find_min_max(numbers):
return min(numbers), max(numbers)

nums = [5, 2, 9, 1]
mn, mx = find_min_max(nums)

print("Minimum:", mn)
print("Maximum:", mx)

✅ Problem 10 – GPS Coordinate Analyzer


locations = (
(12.97, 77.59),
(28.61, 77.20),
(19.07, 72.87)
)

for loc in locations:


print(loc)

print("First location:", locations[0])

✅ Problem 11 – Duplicate Removal Without Set


ids = [1, 2, 2, 3, 4, 4]
unique = []
for i in ids:
if i not in unique:
[Link](i)

print("Unique IDs:", unique)

✅ Problem 12 – List Cloning Demonstration


a = [1, 2, 3]
b = [Link]()

b[0] = 100

print("Original:", a)
print("Clone:", b)

✅ Problem 13 – Sales Data Processing


sales = [100, 200, 150, 300]
avg = sum(sales) / len(sales)

count = 0
for s in sales:
if s > avg:
print("Above average:", s)
count += 1

print("Days above average:", count)

✅ Problem 14 – Tuple Packing and Unpacking


student = ("Ravi", "CSE", 8.5)

name, dept, cgpa = student

print(name)
print(dept)
print(cgpa)
✅ Problem 15 – List Rotation
nums = [1, 2, 3, 4]

last = [Link]()
[Link](0, last)

print("Rotated list:", nums)

Real-Time Set Problems with Answers

1. Unique Website Visitors


Problem
A website records visitor IDs. Some visitors visit multiple times. Find the number of unique
visitors.

Visitor log:

[101,102,103,101,104,102,105]

Solution
visitors = [101,102,103,101,104,102,105]

unique_visitors = set(visitors)

print("Unique Visitors:", unique_visitors)


print("Total Unique Visitors:", len(unique_visitors))

Output
Unique Visitors: {101,102,103,104,105}
Total Unique Visitors: 5
2. Students Enrolled in Two Courses
Problem
Find students enrolled in both Python and AI courses.

Python course students:

{"Ravi","Asha","John","Kiran"}

AI course students:

{"John","Asha","Meena","Rahul"}

Solution
python_students = {"Ravi","Asha","John","Kiran"}
ai_students = {"John","Asha","Meena","Rahul"}

common_students = python_students & ai_students

print("Students enrolled in both courses:", common_students)

Output
Students enrolled in both courses: {'John', 'Asha'}

3. Products Available in Either Store


Problem
Two stores sell different products. Find all products available across both stores.

Solution
store1 = {"Laptop","Mouse","Keyboard"}
store2 = {"Keyboard","Monitor","Mouse"}
all_products = store1 | store2

print("All products:", all_products)

Output
{'Laptop','Mouse','Keyboard','Monitor'}

4. Students Only in Python Course


Problem
Find students who registered only for Python course but not AI course.

Solution
python_students = {"Ravi","Asha","John","Kiran"}
ai_students = {"John","Asha","Meena","Rahul"}

only_python = python_students - ai_students

print("Only Python students:", only_python)

Output
{'Ravi','Kiran'}

5. Students Enrolled in Only One Course


Problem
Find students enrolled in only one course (not both).
Solution
python_students = {"Ravi","Asha","John","Kiran"}
ai_students = {"John","Asha","Meena","Rahul"}

exclusive = python_students ^ ai_students

print("Students in only one course:", exclusive)

Output
{'Ravi','Kiran','Meena','Rahul'}

6. Detect Duplicate Product Codes


Problem
A warehouse system stores product codes. Detect duplicates.

[1001,1002,1003,1001,1004,1002]

Solution
codes = [1001,1002,1003,1001,1004,1002]

unique_codes = set(codes)

duplicates = len(codes) - len(unique_codes)

print("Duplicate items:", duplicates)

Output
Duplicate items: 2
7. Common Skills Between Two Employees
Problem
Find common skills between two employees.

Employee 1:

{"Python","SQL","Machine Learning"}

Employee 2:

{"Python","Java","Machine Learning"}

Solution
emp1 = {"Python","SQL","Machine Learning"}
emp2 = {"Python","Java","Machine Learning"}

common_skills = [Link](emp2)

print("Common skills:", common_skills)

Output
{'Python','Machine Learning'}

8. Unique Characters in Password


Problem
Find unique characters used in a password.

Password:

"PythonProgramming"
Solution
password = "PythonProgramming"

unique_chars = set(password)

print("Unique characters:", unique_chars)

Output
Example:

{'P','y','t','h','o','n','r','g','a','m','i'}

9. Find Missing Subjects


Problem
A student must complete all subjects:

{"Math","Physics","Chemistry","Biology"}

Completed subjects:

{"Math","Physics"}

Find remaining subjects.

Solution
all_subjects = {"Math","Physics","Chemistry","Biology"}
completed = {"Math","Physics"}

remaining = all_subjects - completed

print("Subjects remaining:", remaining)


Output
{'Chemistry','Biology'}

10. Social Media Mutual Friends


Problem
Find mutual friends between two users.

User A:

{"Alex","John","Ravi","Meena"}

User B:

{"Ravi","Meena","David","Sophia"}

Solution
userA = {"Alex","John","Ravi","Meena"}
userB = {"Ravi","Meena","David","Sophia"}

mutual = userA & userB

print("Mutual friends:", mutual)

Output
{'Ravi','Meena'}

Summary of Set Concepts Used


Concept Used In
Creating set All problems
Removing duplicates Problem 1,6
Intersection Problem 2,7,10
Concept Used In
Union Problem 3
Difference Problem 4,9
Symmetric difference Problem 5
Membership logic Problem 8

You might also like