Guide Python Intermediate

10.14 Common Algorithms

Classic list algorithms built from tools covered earlier in this chapter -- reverse, order-preserving deduplication with dict.fromkeys(), find max/min, merging two lists, and splitting one into fixed-size chunks.

2 min read

Reverse

def reverse_list(l):
    return l[::-1]

>>> reverse_list([1, 2, 3])
[3, 2, 1]

Remove Duplicates (Order-Preserving)

dict.fromkeys() removes duplicates while preserving first-seen order — a plain set() would also dedupe, but loses ordering, the same trade-off covered for strings in 9.9 String Algorithms.

def remove_duplicates(l):
    return list(dict.fromkeys(l))

>>> remove_duplicates([1, 2, 2, 3, 1])
[1, 2, 3]

Find Max / Find Min

>>> max([3, 7, 2]), min([3, 7, 2])
(7, 2)

Merge

def merge_lists(a, b):
    return a + b

>>> merge_lists([1, 2], [3, 4])
[1, 2, 3, 4]

Split into Chunks

Splitting a list into fixed-size chunks — a common batching pattern for processing large collections in manageable pieces.

def split_list(l, n):
    return [l[i:i+n] for i in range(0, len(l), n)]

>>> split_list([1, 2, 3, 4, 5, 6, 7], 3)
[[1, 2, 3], [4, 5, 6], [7]]

Quick Interview Answer

“These algorithms all lean on tools already covered in this chapter rather than hand-rolled loops: l[::-1] for reversal, dict.fromkeys(l) for order-preserving deduplication (a plain set() dedupes but drops order), max()/min() for extremes, + for merging two lists into a new one, and a slicing comprehension — l[i:i+n] stepped by n — for chunking a list into fixed-size batches, which is the standard pattern for processing a huge collection or API payload in manageable pieces.”

Common Mistakes

  • Using a plain set(l) to deduplicate when the original order needs to be preserved — sets don’t preserve insertion order; dict.fromkeys(l) does.
  • Forgetting the last chunk from split_list() may be shorter than n if the list doesn’t divide evenly — code consuming the chunks needs to handle a partial final chunk.
  • Using a + b to merge two very large lists repeatedly in a loop instead of list.extend() or building with a single itertools.chain() pass — each + allocates an entirely new list.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form