Pairs of distinct elements and their absolute difference from two lists


Creates a dictionary named abs_diff_dict. This dictionary maps pairs of elements from list1 and list2 to their absolute differences. Here's how the code works:

  • list1 = [3, 6, 9] and list2 = [5, 10, 15]: These lines initialize two lists, list1 and list2, with some integer values.
  • abs_diff_dict = {(x, y): abs(x - y) for x in list1 for y in list2}: This line uses a dictionary comprehension to create the abs_diff_dict dictionary. Here's what happens:
    • (x, y) is used as a tuple to represent pairs of elements, where x is an element from list1 and y is an element from list2.
    • abs(x - y) calculates the absolute difference between x and y for each pair.
    • The dictionary comprehension iterates over all possible pairs of elements from list1 and list2 and computes the absolute difference for each pair, using the tuple (x, y) as the key and the absolute difference as the value.
  • print(list1): This line prints the contents of list1 to the console.
  • print(list2): This line prints the contents of list2 to the console.
  • print(abs_diff_dict): This line prints the abs_diff_dict dictionary, which contains pairs of elements as keys and their absolute differences as values.

Source Code

list1 = [3, 6, 9]
list2 = [5, 10, 15]
abs_diff_dict = {(x, y): abs(x - y) for x in list1 for y in list2}
print(list1)
print(list2)
print(abs_diff_dict)

Output

[3, 6, 9]
[5, 10, 15]
{(3, 5): 2, (3, 10): 7, (3, 15): 12, (6, 5): 1, (6, 10): 4, (6, 15): 9, (9, 5): 4, (9, 10): 1, (9, 15): 6}

Example Programs