Some common algorithms come up over and over again with lists and loops. Here are some to know.
Count items meeting some criteria
Example: count the number of words with at least 6 letters in the words list.
words = ['happy', 'rambunctious', 'sad', 'special', 'eager']
count = 0
for word in words:
if len(word) >= 6:
count += 1
print(count)
In this task, we start with a counter variable set to zero. Then we use an if statement to check if the word meets the len(word) >= 5 criteria, and add to the counter if so.
Find maximum or minimum value
This can also be called finding the “best” value. If we want the maximum value in a list of numbers, the “best” value is the largest value in that case.
In all cases, we use a “best so far” variable, which we update each time we find a “better” value as we traverse the list.
nums = [6, 2, 9, 12, 3, 11]
biggest = nums[0]
for n in nums:
if n > biggest:
biggest = n
print('Maximum: ', biggest)
We start with a biggest variable that equals the first value in our list. At the beginning, this is the largest value we’ve found so far. We look at each number, and every time we find one bigger than the previous biggest number, we update biggest to that new value.
If we wanted the smallest (minimum) value, we would use something like if n < smallest instead, and otherwise the process is the same.
Adding up all values
In this case, we create a total variable with a starting value of zero.Then, we add each value to it using a loop.
values = [2.5, 0.4, 12.5, 7.8]
total = 0
for v in values:
total += v
print('Total =', total)
We can easily modify this program to give other types of results. For example, we get the average if we divide by the length of the list, len(values) at the end.
Modifying each value in a list
If we want to change every value in the original list, we need to be a little careful. Let’s say we want to add 100.00 to the balance of every bank account.
# DOES NOT WORK balances = [213.34, 29.46, 304.60] for b in balances: b += 100.00 print(balances)
This doesn’t work. The values in balances will all be the same as before, because the variable b is a temporary variable that’s only a copy of the value from the original list. The original list is unchanged.
Here’s the way to do it successfully using a counter variable:
balances = [213.34, 29.46, 304.60] for i in range(len(balances)): balances[i] += 100.00 print(balances)
This works because assigning a new value to balances[i] actually changes the real list.
Using for i in range(len(balances)) gives us the index i, which lets us directly access and reassign the value in the list.
Searching for a specific value in a list
Here, we want to print the location (the integer index) of some value within in a list. If the item isn’t in the list at all, it instead prints -1.
pets = ['dog', 'cat', 'bird', 'lizard', 'cat']
x = -1
wanted_pet = 'cat'
for i in range(len(pets)):
if pets[i] == wanted_pet:
x = i
break
print(x)
Note that we again used a counter variable, because using a for pet in pets style of loop doesn’t give us access to the index values that we need.
The starting value of x is -1, so if wanted_pet is never found, the value -1 will be printed at the end.
The break statement causes the loop to quit, giving us the first occurrence of the desired item in our list. If we remove the break, the program will instead give us the index of the last occurrence of the item we’re looking for.
Python lists includes the index() function that does this work for you (see below). This is true for many useful tasks. Still, a programmer should be able to perform simple tasks like this, because many of the more complicated tasks (which don’t have built in functions) require the same type of logic.
pets = ['dog', 'cat', 'bird', 'lizard', 'cat']
x = pets.index('cat')
print(x)
Transform each item into new list
Sometimes we want to use the data from an existing list to create a new version of the list, leaving the original data intact.
In the following example, we start with name strings written like “Andor, Cassian” and make a new list with names written like “Cassian Andor.” (See comments in code)
names = [
'Andor, Cassian',
'Connor, Sarah',
'Picard, Jean-Luc',
'Ripley, Ellen'
]
# Create new empty list
first_last_names = []
# Traverse the original list using loop
for full_name in names:
# Prepare new name string
comma = full_name.find(',')
last = full_name[0:comma]
first = full_name[comma+2:]
output = first + " " + last
# Add to new list
first_last_names.append(output)
# Print new list
for name in first_last_names:
print(name)
A key thing to notice is that we loop through the original list while adding items to the new list.
Other Common Algorithms
Here are some other common list/loops algorithms:
- Filter into a new list – collect items that meet a condition
- Reverse – build a new list backwards or swap items in place
- Sort – simple versions like selection sort or bubble sort
- Frequency count – count how often each item appears
- Find second largest or smallest – track best and second best
- Check membership – manually check if a value exists
- String algorithms – palindrome check, remove or replace characters, concatenate with separators
- While-based removal – keep removing items until a condition is met