Comparing lists in Python 3

A quick run down of comparing lists in Python 3.

Checking if 2 lists are equal

In order to check if 2 lists are equal they must contain exactly the same items in exactly the same order.  For example consider the following lists:

list_1 = [ 1, 2, 3, 4 ]

list_2 = [ 4, 3, 2, 1 ]

And we compare the lists:

print(list_1 == list_2)

This would return ‘False‘, as although the lists contain the same values, they are in a different order.

However if we add a new list that is identical (apart from its name) to the first list and compare them:

list_1 = [ 1, 2, 3, 4 ]

list_2 = [ 4, 3, 2, 1 ]

List_3 = [ 1, 2, 3, 4 ]

print(list_1 == list_3)

We would get True.

Comparing Dictionaries

Dictionaries differ slightly to lists, they are not ordered! And only need to contain the same key-value pairs (in any order) to return true on a comparison.

Given the following example:

dict_1 = { 1:1, 2:2, 3:3, 4:4}

dict_2 = { 2:2, 2:2, 4:4, 3:3}

If we compare the lists:

print(dict_1 == dict_2)

We would get True.