How do I compare lists in Python with examples?

Comparing lists in Python can be done using various methods depending on the requirements, such as checking for equality, finding common elements, or identifying differences. Here are some common techniques to compare lists:

1. Checking for Equality

You can directly compare two lists using the == operator. This checks if both lists contain the same elements in the same order.

list1 = [1, 2, 3] list2 = [1, 2, 3] list3 = [3, 2, 1] print(list1 == list2) # Output: True print(list1 == list3) # Output: False

2. Finding Common Elements

The intersection method helps to find common elements between two lists.

list1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] common_elements = set(list1) & set(list2) print(common_elements) # Output: {3, 4}

3. Identifying Differences

You can find elements that are unique to each list by using the set difference method.

list1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] unique_to_list1 = set(list1) - set(list2) unique_to_list2 = set(list2) - set(list1) print(unique_to_list1) # Output: {1, 2} print(unique_to_list2) # Output: {5, 6}

Python list comparison compare lists in Python Python list equality find common elements Python list differences