Module Contents
1. Lists2. Tuples3. Sets4. Dictionaries5. Comparison & SelectionCoding PracticeTheory Q&A1. Lists
A list stores multiple values in one variable. Lists are ordered, changeable (mutable), and allow duplicate values. They are one of the most commonly used Python data structures.
1.1 Creating a List
Use square brackets [] and separate elements with commas.
marks = [85, 90, 78, 92]
names = ["Ravi", "Anu", "Kiran"]
mixed = [10, "Python", 3.5, True]
- Python creates a list object.
- Each element is stored in sequence.
- The variable points to that list.
1.2 Indexing
Indexing gets one element. Python starts counting from 0.
colors = ["red", "green", "blue", "yellow"]
print(colors[0]) # red
print(colors[2]) # blue
print(colors[-1]) # yellow
print(colors[-2]) # blue
Positive indexes move from the beginning; negative indexes move from the end.
1.3 Slicing
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[3:]) # [40, 50, 60]
print(numbers[::2]) # [10, 30, 50]
print(numbers[::-1]) # reverse copy
The general form is list[start:stop:step]. The stop position is excluded.
1.4 Updating List Elements
marks = [70, 80, 90]
marks[1] = 95
print(marks) # [70, 95, 90]
Because lists are mutable, existing elements can be changed.
1.5 Adding Elements
append()
items = [10, 20]
items.append(30)
print(items) # [10, 20, 30]
extend()
items = [10, 20]
items.extend([30, 40])
print(items) # [10, 20, 30, 40]
insert()
items = [10, 30]
items.insert(1, 20)
print(items) # [10, 20, 30]
append() adds one object at the end, extend() adds elements from an iterable, and insert() adds at a chosen index.
1.6 Removing Elements
items = ["A", "B", "C", "D"]
items.remove("B") # removes first matching value
x = items.pop() # removes and returns last element
y = items.pop(0) # removes and returns index 0
del items[0] # deletes by index
items.clear() # removes everything
remove() uses a value; pop() uses an index and returns the removed item; del deletes by index or slice.1.7 Searching, Length and Membership
names = ["Ravi", "Anu", "Kiran"]
print(len(names))
print("Anu" in names)
print(names.index("Kiran"))
print(names.count("Ravi"))
1.8 Looping Through a List
marks = [80, 90, 75]
for mark in marks:
print(mark)
The loop visits each element one by one.
1.9 Sorting and Reversing
numbers = [40, 10, 30, 20]
numbers.sort()
print(numbers) # [10, 20, 30, 40]
numbers.sort(reverse=True)
print(numbers) # [40, 30, 20, 10]
new_list = sorted(numbers)
reversed_list = list(reversed(numbers))
sort() changes the original list. sorted() returns a new sorted list.
1.10 Copy vs Alias
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]
b = a creates another reference to the same list. Use a.copy() for a shallow copy.
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a) # [1, 2, 3]
print(b) # [1, 2, 3, 4]
1.11 List Comprehension
squares = [x * x for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
evens = [x for x in range(1, 11) if x % 2 == 0]
List comprehensions provide a compact way to build lists from an iterable.
1.12 Nested Lists
students = [
["Ravi", 85],
["Anu", 92],
["Kiran", 78]
]
print(students[0][0]) # Ravi
print(students[1][1]) # 92
A nested list contains other lists. Use multiple indexes to reach inner elements.
2. Tuples
A tuple is an ordered collection that cannot be changed after creation. Tuples are useful when data should remain fixed.
2.1 Creating Tuples
point = (10, 20)
colors = ("red", "green", "blue")
empty = ()
single = (10,) # comma is important
(10) is just the integer 10. (10,) is a one-element tuple.
2.2 Indexing and Slicing
data = ("A", "B", "C", "D")
print(data[0])
print(data[-1])
print(data[1:3])
2.3 Tuple Immutability
numbers = (10, 20, 30)
# numbers[1] = 99 # TypeError
You cannot directly replace, append or remove tuple elements.
2.4 Tuple Packing and Unpacking
# Packing
student = "Ravi", 22, "Python"
# Unpacking
name, age, course = student
print(name)
print(age)
print(course)
Unpacking assigns tuple elements to multiple variables in one statement.
2.5 Tuple Methods
values = (10, 20, 10, 30, 10)
print(values.count(10))
print(values.index(30))
Tuples mainly provide count() and index().
2.6 Tuple vs List
| List | Tuple |
|---|---|
| Mutable | Immutable |
[] | () |
| Good for changing data | Good for fixed data |
3. Sets
A set is a collection of unique elements. It is useful for removing duplicates and performing mathematical set operations.
3.1 Creating a Set
numbers = {10, 20, 30, 20, 10}
print(numbers) # duplicates are removed
empty_set = set()
empty_dict = {} # this is a dictionary, not a set
Do not use {} for an empty set; use set().
3.2 Adding and Updating
colors = {"red", "blue"}
colors.add("green")
colors.update(["yellow", "black"])
print(colors)
3.3 Removing Elements
colors = {"red", "blue", "green"}
colors.remove("blue") # error if missing
colors.discard("black") # no error if missing
item = colors.pop() # removes an arbitrary set element
colors.clear()
3.4 Membership
skills = {"Python", "SQL", "Power BI"}
print("Python" in skills)
print("Java" not in skills)
3.5 Union and Intersection
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union
print(a & b) # intersection
Union contains values from both sets. Intersection contains only common values.
3.6 Difference and Symmetric Difference
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a - b) # only in a
print(b - a) # only in b
print(a ^ b) # in either set, but not both
3.7 Subset, Superset and Disjoint
a = {1, 2}
b = {1, 2, 3, 4}
print(a.issubset(b))
print(b.issuperset(a))
print(a.isdisjoint({7, 8}))
3.8 Frozenset
fixed = frozenset([1, 2, 3])
# fixed.add(4) # not allowed
A frozenset is an immutable set.
4. Dictionaries
A dictionary stores data as key-value pairs. Keys are unique and are used to retrieve values.
4.1 Creating a Dictionary
student = {
"name": "Ravi",
"age": 22,
"course": "Python"
}
4.2 Accessing Values
print(student["name"])
print(student.get("age"))
print(student.get("phone", "Not available"))
dict[key] raises KeyError for a missing key, while get() can return a default value.
4.3 Adding and Updating
student["city"] = "Hyderabad"
student["age"] = 23
student.update({"course": "Data Analytics", "score": 90})
4.4 Removing Items
student = {"name": "Ravi", "age": 22, "city": "Hyderabad"}
age = student.pop("age")
last = student.popitem()
del student["name"]
student.clear()
4.5 keys(), values() and items()
student = {"name": "Ravi", "age": 22}
print(student.keys())
print(student.values())
print(student.items())
4.6 Looping Through a Dictionary
student = {"name": "Ravi", "age": 22}
for key in student:
print(key)
for key, value in student.items():
print(key, value)
4.7 Dictionary Membership
student = {"name": "Ravi", "age": 22}
print("name" in student)
print("Ravi" in student) # checks keys, not values
4.8 Nested Dictionaries
students = {
"S101": {"name": "Ravi", "marks": 85},
"S102": {"name": "Anu", "marks": 92}
}
print(students["S102"]["marks"])
4.9 setdefault()
data = {"name": "Ravi"}
data.setdefault("city", "Hyderabad")
data.setdefault("name", "Anu")
print(data)
setdefault() inserts a key only when it does not already exist.
4.10 Dictionary Comprehension
squares = {x: x * x for x in range(1, 6)}
print(squares)
5. Choosing the Right Data Structure
| Structure | Ordered | Mutable | Duplicates | Indexing | Best use |
|---|---|---|---|---|---|
| List | Yes | Yes | Yes | Yes | Changing ordered collection |
| Tuple | Yes | No | Yes | Yes | Fixed ordered data |
| Set | No guaranteed sequence order | Yes | No | No | Unique values and set operations |
| Dictionary | Insertion-ordered | Yes | Keys unique | By key | Key-value data |
5.1 Practical Selection Rule
- Need an ordered collection that changes? → List
- Need fixed ordered data? → Tuple
- Need unique values or fast membership checks? → Set
- Need to associate a key with a value? → Dictionary
5.2 Common Mistakes
- Using
{}when you need an empty set. - Forgetting that list indexes start at 0.
- Using a tuple when frequent modification is required.
- Expecting a set to support indexing.
- Assuming dictionary membership checks values; it checks keys.
- Confusing
append()withextend(). - Using
remove()when the item might not exist and an exception is undesirable.
5.3 Dry-Run Example
numbers = [10, 20, 30]
numbers.append(40)
numbers[1] = 25
numbers.pop(0)
print(numbers)
- Start:
[10, 20, 30] - append(40):
[10, 20, 30, 40] - index 1 becomes 25:
[10, 25, 30, 40] - pop(0) removes 10:
[25, 30, 40]
30 Coding Questions — Step-by-Step Solutions
Try each question yourself first. Then click the solution button to reveal the explanation and code.
Create a list of five fruits and print the first and last fruit.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
fruits = ["apple", "banana", "mango", "orange", "grapes"]
print(fruits[0])
print(fruits[-1])Print the second and second-last element of a list.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [10, 20, 30, 40, 50]
print(numbers[1])
print(numbers[-2])Print the first three, last two and alternate elements.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[:3])
print(numbers[-2:])
print(numbers[::2])Change the second element of a list to 99.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [10, 20, 30]
numbers[1] = 99
print(numbers)Add 40 to the end of [10, 20, 30].
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [10, 20, 30]
numbers.append(40)
print(numbers)Add [40, 50] to an existing list.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [10, 20, 30]
numbers.extend([40, 50])
print(numbers)Insert 25 between 20 and 30.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [10, 20, 30]
numbers.insert(2, 25)
print(numbers)Remove the value 20 from a list.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [10, 20, 30, 20]
numbers.remove(20)
print(numbers)Remove and print the last element.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [10, 20, 30]
removed = numbers.pop()
print("Removed:", removed)
print(numbers)Find sum, maximum and minimum of a list.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [10, 25, 7, 40, 18]
print("Sum:", sum(numbers))
print("Max:", max(numbers))
print("Min:", min(numbers))Count how many times 10 appears.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [10, 20, 10, 30, 10]
print(numbers.count(10))Sort a list in ascending and descending order.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [40, 10, 30, 20]
numbers.sort()
print(numbers)
numbers.sort(reverse=True)
print(numbers)Reverse a list using reverse().
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers)Create a separate copy and modify only the copy.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
a = [1, 2, 3]
b = a.copy()
b.append(4)
print("a:", a)
print("b:", b)Create squares from 1 to 10 using comprehension.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
squares = [x * x for x in range(1, 11)]
print(squares)Access the marks of the second student.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
students = [["Ravi", 85], ["Anu", 92], ["Kiran", 78]]
print(students[1][1])Create a tuple of three cities and print the last city.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
cities = ("Hyderabad", "Chennai", "Bengaluru")
print(cities[-1])Create a tuple containing only 10.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
value = (10,)
print(value)
print(type(value))Unpack a tuple containing name, age and course.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
student = ("Ravi", 22, "Python")
name, age, course = student
print(name, age, course)Count 10 and find the index of 30.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
values = (10, 20, 10, 30, 10)
print(values.count(10))
print(values.index(30))Convert a list into a tuple.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [10, 20, 30]
numbers_tuple = tuple(numbers)
print(numbers_tuple)Remove duplicates from a list using a set.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
numbers = [10, 20, 10, 30, 20, 40]
unique = set(numbers)
print(unique)Add one value and multiple values to a set.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
skills = {"Python", "SQL"}
skills.add("Excel")
skills.update(["Power BI", "Git"])
print(skills)Find union and common elements of two sets.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print("Union:", a | b)
print("Intersection:", a & b)Find values that exist only in the first set.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a - b)Check whether {1,2} is a subset of {1,2,3}.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
a = {1, 2}
b = {1, 2, 3}
print(a.issubset(b))
print(b.issuperset(a))Create a student dictionary and safely read a missing key.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
student = {"name": "Ravi", "age": 22}
print(student["name"])
print(student.get("phone", "Not available"))Add city and update age.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
student = {"name": "Ravi", "age": 22}
student["city"] = "Hyderabad"
student["age"] = 23
print(student)Print every key and value.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
student = {"name": "Ravi", "age": 22, "course": "Python"}
for key, value in student.items():
print(key, ":", value)Access the marks of student S102.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
students = {
"S101": {"name": "Ravi", "marks": 85},
"S102": {"name": "Anu", "marks": 92}
}
print(students["S102"]["marks"])Create a dictionary of numbers and their cubes.
- Read the requirement and identify the required data structure.
- Create the structure with the correct Python syntax.
- Perform the required operation.
- Print or inspect the result.
cubes = {x: x**3 for x in range(1, 6)}
print(cubes)30 Theory Questions with Answers
Use these for revision, exams and interviews.