How to select N unique random indices from an existing list in Python

1 Answer

0 votes
import random

"""
    Select N unique random indices from an existing list in Python.
    Return the indices and print both the index and the corresponding value.

    Approach:
    - Use random.sample to select N unique indices from range(len(data)).
    - This guarantees uniqueness and avoids manual shuffling.
    - Then print each selected index and its corresponding value.
"""

def pick_unique_indices(size, count):
    if count > size:
        raise ValueError("Cannot pick more unique indices than the list contains.")

    # Select N unique random indices
    return random.sample(range(size), count)


def main():
    # Example list
    data = [5, 12, 5, 19, 5, 33, 47, 5, 58, 61, 17, 3, 5, 74, 83, 90, 6]

    N = 6  # number of unique indices to pick

    # Get unique random indices
    indices = pick_unique_indices(len(data), N)

    # Print results
    print("Random unique indices and their values:")
    for idx in indices:
        print(f"index {idx} -> value {data[idx]}")


if __name__ == "__main__":
    main()


"""
run:

Random unique indices and their values:
index 0 -> value 5
index 1 -> value 12
index 5 -> value 33
index 13 -> value 74
index 15 -> value 90
index 4 -> value 5

"""

 



answered Sep 12 by avibootz
...