
- 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
How do we compare two lists in Python?
The easiest way to do this is use sets. Sets will take the lists and take only unique values. Then you can perform a & operation that acts like intersection to get the common objects from the lists.
example
>>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(a) & set(b) {5}
You can also use set.intersection function to perform this operation.
example
>>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(a).instersection(set(b)) set([5])
- Related Articles
- How do we compare the elements of two lists in Python?
- How do we compare two tuples in Python?
- How do we compare two dictionaries in Python?
- How to compare two lists in Python?
- How do we define lists in Python?
- How do we compare two arrays in Java?
- How do we compare Python Dates?
- How to compare two lists for equality in C#?
- How do we compare String in Java
- How do you add two lists in Java?
- How To Do Math With Lists in python ?
- How can we compare data in two MySQL tables?
- How do we compare the members of enums in Java?
- Dividing two lists in Python
- Merge Two Sorted Lists in Python

Advertisements