How do I iterate equal values with the standard library?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
If you want to iterate equal values in Python using only the standard library, the right tool depends on what “equal values” means in your data. If equal items are already adjacent, itertools.groupby is the natural choice. If you care about frequency rather than adjacency, collections.Counter is often better. The standard library supports both patterns, but they solve different problems.
The key detail is that groupby only groups consecutive equal values. It does not search the entire iterable for matching values unless you sort first or the data is already grouped.
Use itertools.groupby for Consecutive Equal Values
groupby walks through an iterable and emits a new group whenever the key changes.
Output conceptually looks like this:
- '
1with the first consecutive run' - '
2with the next consecutive run' - '
3with its run' - '
1again with the final run'
That last point matters. Because the final 1, 1 appears later, it becomes a separate group. groupby is about runs, not global aggregation.
Sort First If You Want Equal Values Together
If you want every equal value combined into one group, sort the data first.
Now all equal values are adjacent, so groupby produces one group per distinct value.
This pattern is simple and stays entirely in the standard library. It is especially useful when you want to iterate over groups in sorted order.
Group Objects by a Field
groupby becomes even more useful when the elements are objects or records and you want to group by one attribute.
The sorting step is important here too. Without it, equal keys that appear in different parts of the input would not be merged into one group.
Use Counter When You Really Want Counts
Sometimes “iterate equal values” actually means “tell me how many times each value appears.” In that case, Counter is often the better tool.
Counter does not preserve consecutive runs the way groupby does. It aggregates globally by value. That is a different question and a different answer.
Be Careful With Group Iterators
The group object returned by groupby is an iterator tied to the main grouping iterator. If you need to use a group's contents more than once, consume it immediately into a list.
If you try to revisit group later without storing it, you will usually find it has already been consumed.
Common Pitfalls
The biggest mistake is expecting itertools.groupby to collect all equal values across the entire iterable without sorting first. It only groups consecutive equal values.
Another issue is forgetting that the subgroup iterator is one-use. Convert it to a list if you need to inspect it more than once.
A third problem is using groupby when the real goal is just counting frequencies. Counter is simpler for that task.
Summary
- Use
itertools.groupbywhen equal values are already consecutive or when you can sort first. - Remember that
groupbygroups runs, not all matching values across the iterable by default. - Sort by the grouping key if you want one group per distinct value.
- Use
Counterwhen you need global frequency counts instead of run-based groups. - Materialize each group into a list if you need to use it after the loop advances.
Related reading
- How do I iterate through two lists in parallel?
- How do I iterate through two lists in parallel?
- How do I keep Python print from adding newlines or spaces?
- How do I know if a generator is empty from the start?
- How do I load a file into the python console?
- How do I log a Python error with debug information?
- How do I look inside a Python object?
- How do I loop through a list by twos?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.