Create, access, slice and update lists.
๐งบ Lists, Tuples & Sets
Store multiple values, update ordered data, protect fixed records and perform fast uniqueness and membership operations.
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)}")Profile: ('Bhavya', 92)
Unique: 3
By the End of This Level
You will be able to select and use Python collections confidently.
Use list methods for practical data processing.
Store fixed records with tuples and unpack their values.
Use sets for uniqueness, membership and mathematical operations.
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.
The same list object can be changed in place without creating a completely new collection.
[][10, 20, 30]["Python", 3, True]len([4, 8, 12]) โ 3If second = first, both names refer to the same list. Use second = first.copy() when you need an independent shallow copy.
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.
| Expression | Meaning | Result for [10, 20, 30, 40] |
|---|---|---|
values[0] | First element | 10 |
values[-1] | Last element | 40 |
values[1:3] | Indexes 1 and 2 | [20, 30] |
values[::2] | Every second element | [10, 30] |
values[1] = 25 | Replace index 1 | [10, 25, 30, 40] |
Update a Course List
courses = ["Python", "C", "Java"]
courses[1] = "SQL"
print(courses)
print(courses[0:2])['Python', 'SQL', 'Java'] ['Python', 'SQL']
Essential List Methods
| Method | Purpose | Important behaviour |
|---|---|---|
append(value) | Add one value at the end | Changes the list in place |
extend(iterable) | Add several values | Adds each incoming element |
insert(index, value) | Add at a position | Shifts later values right |
remove(value) | Remove first matching value | Raises an error if absent |
pop() | Remove and return an element | Uses the last index by default |
sort() | Sort the same list | Returns None |
reverse() | Reverse the same list | Changes order in place |
count(value) | Count matches | Does not modify the list |
Manage Scores
scores = [72, 91, 84]
scores.append(88)
scores.sort()
print(scores)
print("Highest =", max(scores))[72, 84, 88, 91] Highest = 91
scores.sort() changes scores. sorted(scores) returns a new sorted list and leaves the original collection unchanged.
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.
One Item
Write (5,); the comma creates the tuple.
Unpack a Student Record
student = ("Bhavya", 92, "CSE-AIML")
name, score, branch = student
print(name)
print(score)
print(branch)Bhavya 92 CSE-AIML
Set Fundamentals
A set is an unordered collection of unique hashable values. It is powerful for removing duplicates and testing membership.
set(){2, 4, 6}set([2, 2, 4])"Python" in skills{} creates an empty dictionary, not an empty set. Always use set() for an empty set.
Set Methods and Operations
| Operation | Meaning | Operator / method |
|---|---|---|
| Union | Values in either set | a | b or a.union(b) |
| Intersection | Values common to both | a & b or a.intersection(b) |
| Difference | Values in the first set only | a - b or a.difference(b) |
| Symmetric difference | Values in exactly one set | a ^ b |
| Add | Insert one value | a.add(value) |
| Discard | Remove if present | a.discard(value) |
Find Common Skills
team_a = {"Python", "SQL", "C"}
team_b = {"Python", "Java", "SQL"}
common = team_a & team_b
print(sorted(common))['Python', 'SQL']
List vs Tuple vs Set
Choose a collection from the behaviour your problem requires, not merely from its syntax.
List []
Use for ordered data that may grow, shrink or change.
Tuple ()
Use for ordered records whose structure should stay stable.
Set set()
Use for unique values, membership and group comparisons.
| Property | List | Tuple | Set |
|---|---|---|---|
| Ordered | Yes | Yes | No guaranteed position |
| Mutable | Yes | No | Yes |
| Duplicates | Allowed | Allowed | Removed |
| Indexing | Yes | Yes | No |
| Typical use | Changing sequence | Fixed record | Unique group |
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.
Calculate a Total
marks = [78, 85, 92]
total = 0
for mark in marks:
total += mark
print("Total =", total)
print("Average =", total / len(marks))Total = 255 Average = 85.0
Common Collection Mistakes
second = firstThis creates another reference to the same list; use first.copy() for an independent shallow copy.
(5)This is an integer inside parentheses. Write (5,) to create a tuple.
{}Empty braces create a dictionary. Use set().
scores = scores.sort()sort() changes the list and returns None; call scores.sort() separately.
๐ Lists, Tuples & Sets โ Quick Revision
Review these rules before attempting the quiz and programming problems.
Lists are ordered, mutable and allow duplicates.
List indexing starts at zero and supports negative indexes.
List slices exclude the stop index.
append() adds one value at the end.
sort() changes a list; sorted() returns a new list.
Tuples are ordered but immutable.
A one-item tuple requires a trailing comma.
Sets store unique values and do not support indexing.
& finds intersection and | finds union.
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?
๐ฏ 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.
A problem counts as Solved when its output passes before the official solution is opened.
Begin with Python and C, read one more course, append it and display the updated list.
JavaExpected output: Courses = ['Python', 'C', 'Java']append() with the value returned by input().Python Code Editor
Program Output
Run your program to see the output.
Test Case
courses = ["Python", "C"]
new_course = input()
courses.append(new_course)
print("Courses =", courses)Read three marks into a list and display their total and highest value.
78, 85, 92Expected output: Total = 255 and Highest = 92sum() and max().Python Code Editor
Program Output
Run your program to see the output.
Test Case
marks = [int(input()), int(input()), int(input())]
print("Total =", sum(marks))
print("Highest =", max(marks))Read a student name and score, store them in a tuple and unpack the record.
Bhavya, 92Expected output: Name = Bhavya and Score = 92(name, score), then assign it to two variable names.Python Code Editor
Program Output
Run your program to see the output.
Test Case
student = (input(), int(input()))
name, score = student
print("Name =", name)
print("Score =", score)Convert a list containing duplicates to a set and display the unique values in sorted order.
[2, 4, 2, 6, 4]Expected output: Unique = [2, 4, 6]set(), then pass the result to sorted().Python Code Editor
Program Output
Run your program to see the output.
Test Case
numbers = [2, 4, 2, 6, 4]
unique = set(numbers)
print("Unique =", sorted(unique))Find the skills shared by two teams and display them alphabetically.
{"Python", "SQL", "C"}Team B: {"Python", "Java", "SQL"}Expected output: Common = ['Python', 'SQL']&, then sort the result.Python Code Editor
Program Output
Run your program to see the output.
Test Case
team_a = {"Python", "SQL", "C"}
team_b = {"Python", "Java", "SQL"}
common = team_a & team_b
print("Common =", sorted(common))๐ฏ Match the Collection to the Problem
Choose a sequence when position matters.
Choose a list for mutable data.
Choose a tuple for fixed records.
Choose a set for distinct values.
๐ฌ List Mutation โ Visual Flow
Watch one list change through append, indexed assignment and removal operations.
๐งบ How a Mutable List Changes
1. Create the Original List
The list begins as ['Python', 'C'] with two ordered elements.
๐ Program Tracing โ List Total
Move through a loop and observe how each list value changes the running total.
Click Next to begin tracing.
โ
๐ค Collections โ Interview Questions
Answer aloud before opening each explanation.
What is the main difference between a list and a tuple?
Both are ordered sequences, but lists are mutable while tuples are immutable. Tuples are suitable for fixed records; lists are suitable for changing data.
Why does list.sort() return None?
It sorts the same list in place. Returning None makes the mutation explicit and prevents confusion with functions that create a new collection.
What is the difference between append() and extend()?
append(value) adds one object as one element. extend(iterable) adds each value from an iterable separately.
Why can a set not be indexed?
A set does not organize values by stable positions. It uses hashing for uniqueness and membership, so positional indexing has no meaning.
What is tuple unpacking?
Tuple unpacking assigns collection elements to multiple variables in one statement, such as name, score = student. The number of variables must normally match the number of values.
What is the average time complexity of set membership?
Set membership is O(1) on average because sets use a hash table. A list membership scan is O(n).
๐ก 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.
โ๏ธ Collections โ Extra Practice Questions
- Find the second-largest distinct value in a list.
- Rotate a list one position to the right.
- Separate even and odd numbers into two lists.
- Merge two lists without keeping duplicate values.
- Count how many times a target value appears in a tuple.
- Swap two variables using tuple unpacking.
- Find the union, intersection and differences of two sets.
- Check whether one set is a subset of another.
- Find values that occur in exactly one of two lists.
- 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.
