How do I search tuples in Python across multiple processes?

This guide explores how to search for tuples in Python across multiple processes, leveraging the multiprocessing module for enhanced performance and efficiency.
Python, tuples, multiprocessing, search, parallel processing, multi-core, performance
import multiprocessing

def search_tuples(tuples_list, target):
    return [t for t in tuples_list if target in t]

if __name__ == "__main__":
    tuples_list = [(1, 'apple'), (2, 'banana'), (3, 'orange'), (4, 'grape')]
    target = 'banana'

    # Split the data for multiprocessing
    num_chunks = multiprocessing.cpu_count()
    chunk_size = len(tuples_list) // num_chunks
    chunks = [tuples_list[i:i + chunk_size] for i in range(0, len(tuples_list), chunk_size)]

    with multiprocessing.Pool(processes=num_chunks) as pool:
        results = pool.map(search_tuples, [chunk for chunk in chunks])

    # Combine results
    found_items = [item for sublist in results for item in sublist]
    print(f"Tuples containing {target}: {found_items}")
        

Python tuples multiprocessing search parallel processing multi-core performance