Unit 2: Python data structures - Subjective Questions
ECAP776 • Practice Questions with Detailed Answers
20 questions
Define a Python string. Explain string indexing and slicing with suitable examples.
A string is an immutable sequence of Unicode characters enclosed in single, double, or triple quotation marks.
- Indexing: Each character has a position. Positive indexes begin at
0, while negative indexes begin at-1from the right. - Slicing: The syntax is
string[start:stop:step]. Thestopposition is excluded.
Example:
text = "Python"
text[0] # 'P'
text[-1] # 'n'
text[1:4] # 'yth'
text[::-1] # 'nohtyP'
Attempting text[0] = "J" raises a TypeError because strings are immutable.
Explain commonly used Python string methods and demonstrate any five of them.
String methods return results without changing the original string because strings are immutable.
upper()converts letters to uppercase.lower()converts letters to lowercase.strip()removes leading and trailing whitespace.replace(old, new)replaces occurrences of a substring.split(separator)divides a string into a list.join(iterable)combines strings using a separator.
Example:
value = " Python Programming "
value.upper() # ' PYTHON PROGRAMMING '
value.lower() # ' python programming '
value.strip() # 'Python Programming'
value.replace("Python", "Java") # ' Java Programming '
value.strip().split() # ['Python', 'Programming']
"-".join(["A", "B", "C"]) # 'A-B-C'
The original value remains unchanged unless the returned string is assigned to a variable.
Describe different techniques for formatting strings in Python. Compare f-strings, str.format(), and the % operator.
Python supports several string-formatting techniques:
- f-strings: Place expressions inside braces prefixed by
f. They are concise and readable. str.format(): Uses replacement fields and works in older Python 3 versions.%formatting: An older style based on format specifiers.
Example:
name = "Asha"
score = 92.456
f"{name} scored {score:.2f}" # f-string
"{} scored {:.2f}".format(name, score) # str.format()
"%s scored %.2f" % (name, score) # % operator
All three produce Asha scored 92.46. F-strings are generally preferred because they allow expressions, provide clear formatting syntax, and are usually easier to maintain.
Write and explain a Python program that determines whether a given string is a palindrome after ignoring spaces, punctuation, and letter case.
A palindrome reads the same forward and backward after normalization.
def is_palindrome(text):
cleaned = "".join(
character.lower()
for character in text
if character.isalnum()
)
return cleaned == cleaned[::-1]
print(is_palindrome("A man, a plan, a canal: Panama!"))
Explanation:
isalnum()retains only letters and digits.lower()makes comparison case-insensitive.join()combines the retained characters into one string.cleaned[::-1]creates the reversed string.- Equality comparison returns
Truewhen the normalized text is a palindrome.
For an input of length , normalization and reversal each take time, so the overall time complexity is .
Define a Python list. Explain list creation, indexing, slicing, and mutability with examples.
A list is an ordered, mutable collection that can store duplicate values and objects of different types.
items = [10, "Python", 3.5, 10]
items[0]returns10using positive indexing.items[-1]returns the last value,10.items[1:3]returns["Python", 3.5].items[::-1]returns a reversed copy.
Lists are mutable, so their elements can be changed:
items[1] = "Java"
items.append(True)
After these statements, items becomes [10, "Java", 3.5, 10, True]. Slicing normally creates a new list, whereas assigning to an index modifies the existing list.
Explain the differences among append(), extend(), insert(), remove(), pop(), and del when working with lists.
These operations modify lists in different ways:
append(x)addsxas one item at the end.extend(iterable)adds every item from an iterable.insert(i, x)addsxat indexi.remove(x)deletes the first matching value and raisesValueErrorif absent.pop(i)removes and returns the item at indexi; without an index, it removes the last item.delremoves an item, a slice, or an entire variable.
Example:
values = [1, 2]
values.append([3, 4]) # [1, 2, [3, 4]]
values.extend([5, 6]) # [1, 2, [3, 4], 5, 6]
values.insert(1, 10) # [1, 10, 2, [3, 4], 5, 6]
values.remove(10)
last = values.pop()
del values[0]
The key distinction is that remove() works by value, while pop() and del commonly work by position.
What is list comprehension? Explain its syntax and use it to create filtered and transformed lists.
A list comprehension is a concise way to construct a list by transforming and optionally filtering values from an iterable.
General syntax:
[expression for item in iterable if condition]
Examples:
squares = [number ** 2 for number in range(1, 6)]
# [1, 4, 9, 16, 25]
even_squares = [number ** 2 for number in range(1, 11)
if number % 2 == 0]
# [4, 16, 36, 64, 100]
labels = ["even" if number % 2 == 0 else "odd"
for number in range(5)]
The filtering condition appears after the loop, whereas a conditional expression that selects between two output values appears before the loop. Comprehensions are compact, but deeply nested logic is often clearer as an ordinary loop.
Discuss shallow copying and deep copying of nested Python lists. Why can ordinary list copying produce unexpected results?
An assignment such as second = first creates another reference to the same list; it does not copy the list.
A shallow copy creates a new outer list but shares references to nested objects:
original = [[1, 2], [3, 4]]
shallow = original.copy()
shallow[0].append(99)
Both original[0] and shallow[0] now contain 99 because the inner list is shared. However, replacing shallow[0] would affect only shallow.
A deep copy recursively copies nested mutable objects:
import copy
deep = copy.deepcopy(original)
deep[0].append(100)
This change does not affect original. Other shallow-copy techniques include original[:] and list(original). Deep copying is appropriate when nested mutable data must be modified independently, although it uses additional time and memory.
Define a set in Python. Explain its main properties and the methods used to add and remove elements.
A set is a mutable collection of unique, hashable elements. It does not support positional indexing because it is not a sequence.
values = {1, 2, 2, 3}
# Duplicate 2 is discarded, producing {1, 2, 3}
Main operations include:
add(x)inserts one element.update(iterable)inserts multiple elements.remove(x)deletesxbut raisesKeyErrorif it is absent.discard(x)deletesxwithout raising an error when absent.pop()removes and returns an arbitrary element.clear()removes all elements.
An empty set must be created with set(), because {} creates an empty dictionary. Lists and dictionaries cannot be set elements because they are unhashable, but numbers, strings, and suitable tuples can be elements.
Explain union, intersection, difference, and symmetric difference of sets using operators and methods.
For sets A and B, the principal operations are:
- Union: Elements in either set, written as
A | BorA.union(B). - Intersection: Elements common to both, written as
A & BorA.intersection(B). - Difference: Elements in
Abut notB, written asA - BorA.difference(B). - Symmetric difference: Elements in exactly one set, written as
A ^ BorA.symmetric_difference(B).
Example:
A = {1, 2, 3, 4}
B = {3, 4, 5}
A | B # {1, 2, 3, 4, 5}
A & B # {3, 4}
A - B # {1, 2}
A ^ B # {1, 2, 5}
Union, intersection, and symmetric difference are commutative, but difference is not: generally, .
Distinguish among subset, proper subset, superset, and disjoint sets in Python.
Set relationships describe how the elements of two sets are related.
A <= BorA.issubset(B)means every element ofAis inB.A < BmeansAis a proper subset ofB: it is a subset and is not equal toB.A >= BorA.issuperset(B)meansAcontains every element ofB.A.isdisjoint(B)isTruewhen the sets have no common elements.
Example:
A = {1, 2}
B = {1, 2, 3}
C = {4, 5}
A <= B # True
A < B # True
B >= A # True
A.isdisjoint(C) # True
A set is a subset and a superset of itself, but it is not a proper subset of itself.
Describe practical applications of sets. Write a Python program that finds unique, common, and exclusive values in two lists.
Sets are useful for removing duplicates, membership testing, comparing collections, and implementing mathematical set operations.
first = [1, 2, 2, 3, 4]
second = [3, 4, 4, 5, 6]
set_first = set(first)
set_second = set(second)
unique_first = set_first
unique_second = set_second
common = set_first & set_second
exclusive = set_first ^ set_second
print(unique_first) # {1, 2, 3, 4}
print(unique_second) # {3, 4, 5, 6}
print(common) # {3, 4}
print(exclusive) # {1, 2, 5, 6}
Converting each list to a set removes duplicates. Intersection finds shared values, while symmetric difference finds values present in exactly one collection. Average membership testing in a set takes time, making sets effective for large-scale lookup and duplicate detection.
Define a tuple. Explain tuple creation, packing, unpacking, indexing, and immutability.
A tuple is an ordered, immutable sequence that permits duplicates and mixed data types.
point = (10, 20)
Tuple packing places multiple values into one tuple:
record = "Asha", 19, "Python"
Tuple unpacking assigns its elements to variables:
name, age, course = record
Tuples support indexing and slicing:
point[0] # 10
point[::-1] # (20, 10)
A one-element tuple requires a trailing comma: single = (5,). Parentheses alone do not define a tuple; the comma does. Since tuples are immutable, point[0] = 15 raises TypeError. However, a mutable object stored inside a tuple can still be modified.
Compare lists and tuples in Python. State situations in which a tuple is preferable to a list.
Lists and tuples are both ordered sequences, but they differ in important ways.
- Syntax: Lists use
[]; tuples commonly use(). - Mutability: Lists can be modified; tuples cannot be structurally modified after creation.
- Methods: Lists provide many mutating methods, while tuples mainly provide
count()andindex(). - Performance: Tuples are generally slightly smaller and faster to create or traverse.
- Hashability: A tuple containing only hashable elements can be a dictionary key or set element; a list cannot.
A tuple is preferable for fixed records, coordinates, constant configuration values, multiple return values, and dictionary keys. A list is preferable when elements must be inserted, deleted, reordered, or replaced frequently.
Explain extended tuple unpacking and swapping of variables with suitable Python examples.
Tuple unpacking assigns iterable elements to multiple variables in one statement.
first, second = (10, 20)
Extended unpacking uses one starred target to collect remaining elements into a list:
head, *middle, tail = (1, 2, 3, 4, 5)
# head = 1, middle = [2, 3, 4], tail = 5
It can also ignore unwanted values:
name, *_ = ("Asha", 19, "Python")
Python swaps variables without a temporary variable through packing and unpacking:
x = 5
y = 8
x, y = y, x
The right-hand expressions are evaluated first and conceptually packed; their values are then unpacked into the left-hand targets. Without a starred target, the number of variables must equal the number of elements.
Analyze immutability and hashability in relation to tuples. Under what conditions can a tuple be used as a dictionary key?
Tuple immutability means that its element references cannot be added, removed, or replaced after creation. Hashability additionally requires an object to have a stable hash value and valid equality behavior.
A tuple is hashable only when all of its elements are hashable:
locations = {(10, 20): "Office"} # Valid
The tuple (10, 20) contains integers, which are hashable. In contrast:
invalid = ([10, 20], "Office")
data = {invalid: 1} # Raises TypeError
Although the outer tuple is immutable, it contains a list, which is mutable and unhashable. Therefore, the whole tuple is unhashable. Nested tuples are valid when every value at every level is hashable. This rule ensures that dictionary keys do not change in a way that invalidates their stored hash location.
Define a Python dictionary. Explain how key-value pairs are created, accessed, updated, added, and deleted.
A dictionary is a mutable mapping from unique, hashable keys to values. Values may be duplicated and may have any type.
student = {"name": "Asha", "marks": 88}
Common operations are:
- Access:
student["name"]returns"Asha". - Safe access:
student.get("grade", "Not assigned")returns a default if the key is absent. - Update:
student["marks"] = 92changes an existing value. - Add:
student["grade"] = "A"creates a new pair. - Delete:
del student["grade"]removes a pair. - Remove and return:
student.pop("marks")returns the removed value. - Remove all:
student.clear()empties the dictionary.
Using square brackets for a missing key raises KeyError, whereas get() does not. Dictionaries preserve insertion order in modern Python, but values are retrieved logically by key rather than by numeric position.
Explain important dictionary methods and different ways to iterate over a dictionary.
Important dictionary methods include:
keys()returns a dynamic view of keys.values()returns a dynamic view of values.items()returns a dynamic view of(key, value)pairs.get(key, default)safely retrieves a value.update(mapping)adds pairs and overwrites matching keys.setdefault(key, default)returns an existing value or inserts the default.pop(key)removes a specified pair.popitem()removes and returns the most recently inserted pair.
Iteration examples:
scores = {"Asha": 90, "Ravi": 84}
for name in scores:
print(name)
for score in scores.values():
print(score)
for name, score in scores.items():
print(name, score)
Direct dictionary iteration processes keys. The items() method is normally the clearest choice when both keys and values are required.
What is dictionary comprehension? Use it to create, transform, and filter dictionary entries.
A dictionary comprehension constructs a dictionary from an iterable using key and value expressions.
General syntax:
{key_expression: value_expression
for item in iterable
if condition}
Examples:
squares = {number: number ** 2 for number in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
prices = {"pen": 10, "book": 80, "bag": 500}
discounted = {
item: price * 0.9
for item, price in prices.items()
if price >= 80
}
The second comprehension filters out prices below 80 and transforms retained prices by applying a discount. If multiple generated entries have the same key, the later value replaces the earlier one because dictionary keys must be unique.
Design and explain a Python program that counts word frequencies in a sentence using a dictionary, and discuss its complexity.
A frequency dictionary stores each normalized word as a key and its count as the corresponding value.
import string
def word_frequencies(sentence):
cleaned = sentence.lower().translate(
str.maketrans("", "", string.punctuation)
)
frequencies = {}
for word in cleaned.split():
frequencies[word] = frequencies.get(word, 0) + 1
return frequencies
result = word_frequencies("Python is simple, and Python is powerful.")
print(result)
Output:
{'python': 2, 'is': 2, 'simple': 1, 'and': 1, 'powerful': 1}
Explanation:
lower()makes counting case-insensitive.translate()removes punctuation.split()obtains individual words.get(word, 0)supplies zero for a word not yet present.
If the input contains characters and words, processing takes approximately time with average dictionary access per word. Space usage is , where is the number of distinct words.
Define a Python string. Explain string indexing and slicing with suitable examples.
A string is an immutable sequence of Unicode characters enclosed in single, double, or triple quotation marks.
- Indexing: Each character has a position. Positive indexes begin at
0, while negative indexes begin at-1from the right. - Slicing: The syntax is
string[start:stop:step]. Thestopposition is excluded.
Example:
text = "Python"
text[0] # 'P'
text[-1] # 'n'
text[1:4] # 'yth'
text[::-1] # 'nohtyP'
Attempting text[0] = "J" raises a TypeError because strings are immutable.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →