Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

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
...