﻿ Python: Difference between the two lists - w3resource

# Python: Difference between the two lists

## Python List: Exercise - 19 with Solution

Write a Python program to calculate the difference between the two lists. Sample Solution:

Python Code:

``````list1 = [1, 3, 5, 7, 9]
list2=[1, 2, 4, 6, 7, 8]
diff_list1_list2 = list(set(list1) - set(list2))
diff_list2_list1 = list(set(list2) - set(list1))
total_diff = diff_list1_list2 + diff_list2_list1
print(total_diff)
```
```

Sample Output:

```[9, 3, 5, 8, 2, 4, 6]
```

Explanation:

In the above exercise -

• list1 = [1, 3, 5, 7, 9]: Creates a list list1 with the values [1, 3, 5, 7, 9].
• list2=[1, 2, 4, 6, 7, 8]: Creates a list list2 with the values [1, 2, 4, 6, 7, 8].
• diff_list1_list2 = list(set(list1) - set(list2)): Creates a list diff_list1_list2 containing the elements that are in list1 but not in list2. This is done by converting list1 and list2 to sets and performing set difference (-) operation between them. The resulting set is then converted back to a list diff_list1_list2.
• diff_list2_list1 = list(set(list2) - set(list1)): Creates a list diff_list2_list1 containing the elements that are in list2 but not in list1. This is done by converting list2 and list1 to sets and performing set difference (-) operation between them. The resulting set is then converted back to a list diff_list2_list1.
• total_diff = diff_list1_list2 + diff_list2_list1: Combines the elements in both difference lists diff_list1_list2 and diff_list2_list1 into a single list.
• print(total_diff): Finally print() function prints the resulting list containing the differences between the two lists, which in this case would be [3, 5, 9, 2, 4, 6, 8].

Flowchart: ## Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Python: Tips of the Day

Given a predicate function, fn, and a prop string, this curried function will then take an object to inspect by calling the property and passing it to the predicate:

Example:

```def tips_check_prop(fn, prop):
return lambda obj: fn(obj[prop])
check_age = tips_check_prop(lambda x: x >= 25, 'age')
user = {'name': 'Owen', 'age': 25}

print(check_age(user))
```

Output:

```True
```

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook