Python
Iteration
Standard Library
Equal Values
Programming Tips

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.

Browse interview questions

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.

python
1from itertools import groupby
2
3values = [1, 1, 2, 2, 2, 3, 1, 1]
4
5for key, group in groupby(values):
6    items = list(group)
7    print(key, items)

Output conceptually looks like this:

  • '1 with the first consecutive run'
  • '2 with the next consecutive run'
  • '3 with its run'
  • '1 again 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.

python
1from itertools import groupby
2
3values = [3, 1, 2, 1, 2, 2, 3]
4
5for key, group in groupby(sorted(values)):
6    print(key, list(group))

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.

python
1from itertools import groupby
2from operator import itemgetter
3
4rows = [
5    {"team": "A", "name": "Mina"},
6    {"team": "A", "name": "Raj"},
7    {"team": "B", "name": "Eli"},
8]
9
10rows.sort(key=itemgetter("team"))
11
12for team, members in groupby(rows, key=itemgetter("team")):
13    print(team, [member["name"] for member in members])

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.

python
1from collections import Counter
2
3values = [3, 1, 2, 1, 2, 2, 3]
4counts = Counter(values)
5
6for value, count in counts.items():
7    print(value, count)

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.

python
1from itertools import groupby
2
3for key, group in groupby([1, 1, 2, 2]):
4    group_list = list(group)
5    print(key, group_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.groupby when equal values are already consecutive or when you can sort first.
  • Remember that groupby groups runs, not all matching values across the iterable by default.
  • Sort by the grouping key if you want one group per distinct value.
  • Use Counter when 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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.