Unit 3: Strings and Lists; Tuples and Dictionaries - Subjective Questions
ECE181 — Introduction To Python • Practice Questions with Detailed Answers
20 questions
Explain why a string is called a compound data type in Python. Illustrate with an example how individual characters can be accessed using indexing.
A compound data type is a type made up of smaller pieces (components) that can be broken down further. A string is compound because it is a sequence of individual characters.
Key points:
- A string is an ordered collection of characters.
- Each character can be accessed using its index.
- Indexing starts at
0for the first character. - Negative indices count from the end (
-1is the last character).
Example:
python
fruit = "banana"
print(fruit[0]) # b
print(fruit[1]) # a
print(fruit[-1]) # a (last character)
Because the string can be decomposed into its constituent characters, it qualifies as a compound data type, unlike simple types such as int or float.
Describe how the length of a string is determined in Python. How can you use the length to access the last character safely?
The length of a string is the number of characters it contains, found using the built-in len() function.
Details:
len(s)returns an integer equal to the count of characters.- Valid indices range from
0tolen(s) - 1. - Accessing
s[len(s)]raises anIndexError.
Accessing the last character safely:
python
s = "python"
length = len(s) # 6
last = s[length - 1] # 'n'
Or simply:
last = s[-1] # 'n'
Important: Using s[len(s) - 1] avoids the out-of-range error that s[len(s)] would cause. The negative index s[-1] is a cleaner alternative that automatically points to the final character.
Explain string traversal in Python. Write programs to traverse a string using both a while loop and a for loop.
String traversal means visiting each character of a string one at a time, usually to process or examine them.
1. Using a while loop (index based):
python
s = "hello"
index = 0
while index < len(s):
print(s[index])
index += 1
2. Using a for loop (character based):
python
s = "hello"
for ch in s:
print(ch)
Comparison:
- The while loop uses an index counter and requires manual increment and bound checking.
- The for loop is more concise and directly iterates over each character (Pythonic way).
Both loops output each character on a separate line. Traversal forms the basis of counting, searching, and transforming strings.
What are string slices? Explain the slicing syntax s[start:stop:step] with suitable examples covering default values and negative indices.
A string slice is a substring extracted from a string using the slicing operator [start:stop:step].
Rules:
start: index where the slice begins (inclusive). Default is0.stop: index where the slice ends (exclusive). Default islen(s).step: gap between characters. Default is1.
Examples:
python
s = "programming"
print(s[0:4]) # 'prog'
print(s[:4]) # 'prog' (start defaults to 0)
print(s[4:]) # 'ramming' (stop defaults to end)
print(s[:]) # 'programming' (whole string)
print(s[::2]) # 'pormig' (every 2nd character)
print(s[::-1]) # 'gnimmargorp' (reversed)
print(s[-4:-1]) # 'min'
Key insight: Slicing never raises an IndexError for out-of-range values; it simply clips to valid bounds. A negative step reverses the direction of traversal.
Explain how string comparison works in Python. Describe the role of lexicographic ordering with examples.
Strings in Python are compared using relational operators (==, !=, <, >, <=, >=) based on lexicographic (dictionary) ordering using the Unicode code point of each character.
How it works:
- Characters are compared one by one from left to right.
- The first differing character decides the result.
- Uppercase letters have smaller code points than lowercase (e.g.,
'A'= 65,'a'= 97).
Examples:
python
print("apple" == "apple") # True
print("apple" < "banana") # True ('a' < 'b')
print("Apple" < "apple") # True ('A'=65 < 'a'=97)
print("cat" < "cattle") # True (prefix is smaller)
print("Zoo" < "apple") # True ('Z'=90 < 'a'=97)
Important note: Because of case sensitivity, all uppercase letters sort before lowercase ones. For case-insensitive comparison, convert both strings using .lower().
Describe the find() function for strings. Explain its parameters and return values, and write a function of your own that mimics find().
The find() method searches for a substring within a string and returns the index of its first occurrence.
Syntax: str.find(sub[, start[, end]])
sub: the substring to search for.start(optional): index to begin the search.end(optional): index to end the search.- Returns: the lowest index where
subis found, or-1if not found.
Examples:
python
s = "banana"
print(s.find("a")) # 1
print(s.find("a", 2)) # 3
print(s.find("x")) # -1
Custom implementation:
python
def my_find(word, ch):
index = 0
while index < len(word):
if word[index] == ch:
return index
index += 1
return -1
print(my_find("banana", "n")) # 2
The custom function traverses the string and returns the first matching index, or -1 if the character is absent.
Explain the concept of looping and counting in strings. Write a program to count the number of occurrences of a particular character in a string.
Looping and counting is a common pattern where a loop traverses a string and a counter variable is incremented whenever a condition is met.
Steps:
- Initialize a counter to
0. - Loop through each character.
- Increment the counter on each match.
Program to count occurrences:
python
def count_char(word, ch):
count = 0
for letter in word:
if letter == ch:
count += 1
return count
print(count_char("banana", "a")) # 3
print(count_char("mississippi", "s")) # 4
Explanation:
- The counter (
count) accumulates the total. - The loop examines every character.
- The
ifcondition filters matches.
This pattern generalizes to counting vowels, digits, spaces, or any condition, forming a fundamental building block in text processing.
What are lists in Python? Explain the different types of list values they can store, and how lists differ from strings.
A list is an ordered, mutable collection of items enclosed in square brackets [ ] and separated by commas.
List values can be:
- Numbers:
[1, 2, 3] - Strings:
["a", "b", "c"] - Mixed types:
[1, "hello", 3.14, True] - Nested lists:
[[1, 2], [3, 4]] - Empty:
[]
Example:
python
numbers = [10, 20, 30]
mixed = [1, "two", 3.0, [4, 5]]
empty = []
Differences from strings:
| Feature | String | List |
|---|---|---|
| Mutability | Immutable | Mutable |
| Element type | Only characters | Any data type |
| Modification | Not allowed in place | Allowed |
Key point: Lists are mutable, meaning individual elements can be changed, added, or removed, whereas strings cannot be altered once created.
Explain membership and length operations on lists. Illustrate with the in, not in operators and the len() function.
Length and membership are two fundamental list operations.
1. Length using len():
- Returns the number of elements in a list.
python
nums = [10, 20, 30, 40]
print(len(nums)) # 4
print(len([])) # 0
2. Membership using in / not in:
inreturnsTrueif an element exists in the list.not inreturnsTrueif it does not exist.
python
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("mango" in fruits) # False
print("mango" not in fruits) # True
Nested list note:
python
nested = [[1, 2], [3, 4]]
print([1, 2] in nested) # True
print(1 in nested) # False (1 is not a top-level element)
Key point: Membership checks only top-level elements, and len() counts only the outermost elements even in nested lists.
Describe the various list operations in Python including concatenation, repetition, and slicing with suitable examples.
Python provides several operations to manipulate lists.
1. Concatenation (+): joins two lists.
python
a = [1, 2, 3]
b = [4, 5]
print(a + b) # [1, 2, 3, 4, 5]
2. Repetition (*): repeats list elements.
python
print([0] 4) # [0, 0, 0, 0]
print([1, 2] 3) # [1, 2, 1, 2, 1, 2]
3. Slicing ([start:stop:step]): extracts a sublist.
python
nums = [10, 20, 30, 40, 50]
print(nums[1:4]) # [20, 30, 40]
print(nums[:3]) # [10, 20, 30]
print(nums[::-1]) # [50, 40, 30, 20, 10]
4. Modifying via slices:
python
nums[1:3] = [99, 98]
print(nums) # [10, 99, 98, 40, 50]
Key point: Concatenation and repetition create new lists, while slice assignment can modify an existing list in place.
Explain the different ways to perform deletion of elements from a list in Python. Describe del, remove(), and pop() with examples.
Python offers three main techniques to delete list elements.
1. del statement (by index or slice):
python
nums = [10, 20, 30, 40]
del nums[1] # removes element at index 1
print(nums) # [10, 30, 40]
del nums[0:2] # removes a slice
print(nums) # [40]
2. remove() method (by value):
python
colors = ["red", "green", "blue"]
colors.remove("green") # removes first matching value
print(colors) # ['red', 'blue']
3. pop() method (by index, returns value):
python
items = [1, 2, 3]
x = items.pop() # removes & returns last -> 3
y = items.pop(0) # removes & returns index 0 -> 1
print(items) # [2]
Summary:
- Use
delto delete by index/slice (no return). - Use
remove()to delete by value. - Use
pop()when you need the removed value returned.
Note: remove() raises ValueError if the value is absent; pop() raises IndexError on an empty list.
Explain how to access elements of a list and traverse a list using for loops. Demonstrate accessing by index and by value.
Accessing elements: List elements are accessed by their index using square brackets.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last element)Traversal using a for loop by value:
python
for fruit in fruits:
print(fruit)
Traversal using index (with range and len):
python
for i in range(len(fruits)):
print(i, fruits[i])
Using enumerate() for both index and value:
python
for index, fruit in enumerate(fruits):
print(index, fruit)
Key points:
- Direct iteration (
for fruit in fruits) is cleanest when only values are needed. - Use
range(len(...))orenumerate()when the index is also required. - Negative indices allow access from the end of the list.
Explain list as parameters to functions. Discuss with an example how lists are passed and why changes inside a function affect the original list.
When a list is passed as a parameter to a function, Python passes a reference to the same list object (pass-by-object-reference). Therefore, modifications made inside the function affect the original list.
Example (mutation affects original):
python
def add_item(my_list):
my_list.append(100)
nums = [1, 2, 3]
add_item(nums)
print(nums) # [1, 2, 3, 100]
Example (reassignment does NOT affect original):
python
def reassign(my_list):
my_list = [9, 9, 9] # creates a new local list
nums = [1, 2, 3]
reassign(nums)
print(nums) # [1, 2, 3]
Explanation:
- In-place methods (
append,remove,sort) modify the shared object. - Reassignment (
my_list = ...) only changes the local variable to point elsewhere, leaving the original untouched.
Tip: To avoid unintended side effects, pass a copy using my_list[:] or list(my_list).
What are nested lists? Explain how to create and access elements of a nested list, and write a program to print a matrix using nested lists.
A nested list is a list that contains other lists as its elements. It is commonly used to represent matrices or tables.
Creating a nested list:
python
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Accessing elements (row, column):
python
print(matrix[0]) # [1, 2, 3] (first row)
print(matrix[0][2]) # 3 (row 0, column 2)
print(matrix[2][1]) # 8 (row 2, column 1)
Program to print a matrix:
python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=" ")
print()
Output:
1 2 3
4 5 6
7 8 9
Key point: A nested list requires double indexing matrix[i][j] — the first index selects the inner list (row) and the second selects the element (column).
Define a tuple. Explain how tuples are created and describe why tuples are considered immutable, comparing them with lists.
A tuple is an ordered, immutable collection of items, usually written inside parentheses ( ) and separated by commas.
Creating tuples:
python
t1 = (1, 2, 3)
t2 = 4, 5, 6 # parentheses optional
t3 = (7,) # single-element tuple (comma required)
t4 = () # empty tuple
t5 = tuple([1, 2, 3]) # from a list
Immutability:
python
t = (10, 20, 30)
t[0] = 99 -> TypeError: 'tuple' object does not support item assignment
Once created, a tuple's elements cannot be changed, added, or removed.
Tuple vs List:
| Feature | Tuple | List |
|---|---|---|
| Syntax | ( ) |
[ ] |
| Mutability | Immutable | Mutable |
| Speed | Faster | Slower |
| Use case | Fixed data | Changing data |
Key point: The single-element tuple must include a trailing comma; (7) is just an integer, whereas (7,) is a tuple.
Explain the various operations on tuples such as indexing, slicing, concatenation, repetition, and tuple assignment (packing and unpacking) with examples.
Tuples support several operations similar to lists, but they cannot be modified in place.
1. Indexing & Slicing:
python
t = (10, 20, 30, 40)
print(t[1]) # 20
print(t[-1]) # 40
print(t[1:3]) # (20, 30)
2. Concatenation (+):
python
print((1, 2) + (3, 4)) # (1, 2, 3, 4)
3. Repetition (*):
python
print((0,) * 3) # (0, 0, 0)
4. Membership & Length:
python
print(20 in t) # True
print(len(t)) # 4
5. Tuple packing and unpacking:
python
point = 3, 4 # packing
x, y = point # unpacking
print(x, y) # 3 4
Swapping values
a, b = 5, 10
a, b = b, a
print(a, b) # 10 5
Key point: Concatenation and repetition create new tuples. Tuple unpacking makes multiple assignments and value swapping elegant and concise.
What is a dictionary in Python? Explain how to create a dictionary and add, modify, and retrieve values with examples.
A dictionary is an unordered (insertion-ordered from Python 3.7+) collection of key-value pairs, enclosed in curly braces { }. Keys must be unique and immutable; values can be any type.
Creating a dictionary:
python
student = {"name": "Alice", "age": 20, "grade": "A"}
empty = {}
using_dict = dict(a=1, b=2)
Adding a new key-value pair:
python
student["city"] = "Delhi"
print(student)
{'name': 'Alice', 'age': 20, 'grade': 'A', 'city': 'Delhi'}
Modifying an existing value:
python
student["age"] = 21 # updates existing key
Retrieving values:
python
print(student["name"]) # Alice
print(student.get("grade")) # A
print(student.get("phone", "N/A")) # N/A (default if missing)
Key point: Using dict[key] raises KeyError if the key is absent, whereas get() safely returns None (or a default) without an error. Assigning to a new key adds it; assigning to an existing key updates it.
Explain how to delete items from a dictionary. Describe del, pop(), popitem(), and clear() with examples.
Python provides several ways to remove entries from a dictionary.
1. del statement: deletes a key-value pair by key.
python
d = {"a": 1, "b": 2, "c": 3}
del d["b"]
print(d) # {'a': 1, 'c': 3}
2. pop(key): removes the key and returns its value.
python
val = d.pop("a")
print(val) # 1
print(d) # {'c': 3}
3. popitem(): removes and returns the last inserted key-value pair as a tuple.
python
d = {"x": 10, "y": 20}
item = d.popitem()
print(item) # ('y', 20)
4. clear(): removes all items, leaving an empty dictionary.
python
d.clear()
print(d) # {}
Summary:
del d[key]andpop(key)remove a specific key (popreturns the value).popitem()removes the last pair.clear()empties the whole dictionary.
Note: del and pop() raise KeyError if the key does not exist (unless pop is given a default).
Describe the important dictionary methods in Python such as keys(), values(), items(), get(), update(), and copy() with examples.
Dictionaries provide several built-in methods for accessing and manipulating data.
1. keys() – returns all keys.
python
d = {"a": 1, "b": 2}
print(d.keys()) # dict_keys(['a', 'b'])
2. values() – returns all values.
python
print(d.values()) # dict_values([1, 2])
3. items() – returns key-value pairs as tuples.
python
print(d.items()) # dict_items([('a', 1), ('b', 2)])
for k, v in d.items():
print(k, v)
4. get(key, default) – safely retrieves a value.
python
print(d.get("c", 0)) # 0
5. update() – merges another dictionary.
python
d.update({"c": 3})
print(d) # {'a': 1, 'b': 2, 'c': 3}
6. copy() – returns a shallow copy.
python
d2 = d.copy()
Key point: keys(), values(), and items() return view objects that dynamically reflect changes to the dictionary, and are commonly used for iteration.
Discuss the common operations on dictionaries including traversal, membership testing, and building a dictionary from data. Write a program to count the frequency of each character in a string using a dictionary.
Dictionaries support several operations useful in data processing.
1. Traversal:
python
d = {"a": 1, "b": 2, "c": 3}
for key in d: # iterate keys
print(key, d[key])
for k, v in d.items(): # iterate key-value pairs
print(k, v)
2. Membership testing (in): checks keys only.
python
print("a" in d) # True
print(1 in d) # False (checks keys, not values)
3. Length:
python
print(len(d)) # 3
4. Program – character frequency counter:
python
def char_frequency(text):
freq = {}
for ch in text:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
return freq
print(char_frequency("banana"))
{'b': 1, 'a': 3, 'n': 2}
Explanation:
- The dictionary
freqmaps each character to its count. - If the character exists, its count is incremented; otherwise it is initialized to
1.
Key point: Dictionaries provide fast O(1) average-time lookups, making them ideal for counting and grouping tasks. Membership tests operate on keys, not values.
Explain why a string is called a compound data type in Python. Illustrate with an example how individual characters can be accessed using indexing.
A compound data type is a type made up of smaller pieces (components) that can be broken down further. A string is compound because it is a sequence of individual characters.
Key points:
- A string is an ordered collection of characters.
- Each character can be accessed using its index.
- Indexing starts at
0for the first character. - Negative indices count from the end (
-1is the last character).
Example:
python
fruit = "banana"
print(fruit[0]) # b
print(fruit[1]) # a
print(fruit[-1]) # a (last character)
Because the string can be decomposed into its constituent characters, it qualifies as a compound data type, unlike simple types such as int or float.
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 →