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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,683 questions

55,435 answers

573 users

How to find the N smallest values in a 2D list in Python

1 Answer

0 votes
import heapq

"""
    Find the N smallest values in a 2D array.

    Approach:
    1. Flatten the 2D array into a single list.
    2. Use heapq.nsmallest, which efficiently extracts the smallest N values
       without sorting the entire dataset.
    3. Print the result.

    This keeps the code expressive and efficient while relying on
    Python's built‑in algorithms.
"""

def flatten(matrix):
    """Flatten a 2D list into a 1D list."""
    return [value for row in matrix for value in row]


def smallest_n(matrix, n):
    """Return the N smallest values using an efficient heap-based selection."""
    flat = flatten(matrix)
    
    return heapq.nsmallest(n, flat)


def main():
    matrix = [
        [42, 12, 85,  3],
        [ 7, 99, 15, 23],
        [64,  1, 18, 30],
        [ 3, 55, 11, 90]
    ]

    n = 5

    values = smallest_n(matrix, n)

    print(f"The {n} smallest values:")
    print(*values)


if __name__ == "__main__":
    main()


"""
run:

The 5 smallest values:
1 3 3 7 11

"""

 



answered 2 days ago by avibootz
...