import random


def reservoir_sampling(iter, k):
    """
    Samples k elements from a stream of data using the reservoir sampling
    algorithm.
    """
    res = []
    n = 0
    for item in iter:
        n += 1
        if len(res) < k:
            res.append(item)
        else:
            idx = random.randint(0, n - 1)
            if idx < k:
                res[idx] = item
    return res