- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Program to find minimum difference between two elements from two lists in Python

Suppose we have two lists L1 and L2, we have to find the smallest difference between a number from L1 and a number from L2.

So, if the input is like L1 = [2, 7, 4], L2 = [16, 10, 11], then the output will be 3, as the smallest difference is 10 - 7 = 3.

To solve this, we will follow these steps −

- sort the list L1 and sort the list L2
- ans := infinity
- i := 0, j := 0
- while i < size of L1 and j < size of L2, do
- ans := minimum of ans and |L1[i] - L2[j]|
- if L1[i] < L2[j], then
- i := i + 1

- otherwise,
- j := j + 1

- return ans

Let us see the following implementation to get better understanding −

## Example

class Solution: def solve(self, L1, L2): L1.sort() L2.sort() ans = float("inf") i = j = 0 while i < len(L1) and j < len(L2): ans = min(ans, abs(L1[i] - L2[j])) if L1[i] < L2[j]: i += 1 else: j += 1 return ans ob = Solution() L1 = [2, 7, 4] L2 = [16, 10, 11] print(ob.solve(L1, L2))

## Input

[2, 7, 4], [16, 10, 11]

## Output

3

- Related Articles
- Python program to list the difference between two lists.
- Program to interleave list elements from two linked lists in Python
- Program to find smallest difference between picked elements from different lists in C++
- C# program to list the difference between two lists
- Adding two Python lists elements
- Python program to find difference between two timestamps
- Python program to find Intersection of two lists?
- Python program to find Cartesian product of two lists
- Python program to print all the common elements of two lists.
- Find the minimum difference between Shifted tables of two numbers in Python
- Find minimum difference between any two element in C++
- Minimum Index Sum for Common Elements of Two Lists in C++
- C++ program to find minimum difference between the sums of two subsets from first n natural numbers
- Program to find union of two given linked lists in Python
- Python program to find missing and additional values in two lists?

Advertisements