Just sort the list and select the largest of the products from the last 2 items in the list and the first 2 items in the list:
from operator import mul numbers = [10, 20, 1, -11, 100, -12] l = sorted(numbers)
This solution is O (n log n) due to sorting. Someone else suggested a heapq solution, which, it seemed to me, was faster for lists longer than several thousand random numbers.
source share