In today’s blog, let’s explore how to perform common list operations in Python without using any built-in methods such as .index() or set(). These exercises are great for sharpening your understanding of how things work under the hood.
Problem One: Find the First Index of a Value
You are given a list of
nintegers. Your task is to find the zero-based index of the first occurrence of a specific value in the list. If the value isn’t found, return -1.
Constraint:
You cannot use the built-in .index() method.
Breakdown:
- Loop through the list using indices (
for i in range(len(lst))). - At each step, check if the current element equals the value.
- If it does, return the current index.
- If the loop ends without finding the value, return
-1.
def find_first_index(lst, val):
for i in range(len(lst)): # we check every index manually
if lst[i] == val:
return i
return -1
Example:
print(find_first_index([5, 3, 7, 3, 9], 3)) # Output: 1
print(find_first_index([1, 2, 3], 4)) # Output: -1
Problem Two: Count Unique Elements
You are given a list of integers. Return the number of elements that appear only once in the list.
Constraint:
No use of set(), collections.Counter(), or any built-in helper functions.
Breakdown:
- Initialize a
unique_countto keep track of how many unique elements we find. - Loop through each element
iin the list. - For each
i, run an inner loopjto count how many timeslst[i] == lst[j]. - If the count is exactly 1, increment
unique_count.
def count_unique_elements(lst):
unique_count = 0
for i in range(len(lst)):
count = 0
for j in range(len(lst)):
if lst[i] == lst[j]:
count += 1
if count == 1:
unique_count += 1
return unique_count
Example:
print(count_unique_elements([1, 2, 3, 2, 4])) # Output: 3 (1, 3, 4 are unique)
print(count_unique_elements([1, 1, 1, 1])) # Output: 0
Why This Matters:
Avoiding built-in methods helps you build stronger algorithmic thinking and gives you a deeper appreciation of what’s going on behind the scenes in Python.
Top comments (0)