Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python compare items in 2 list of different length - order is important

list_1 = ['a', 'a', 'a', 'b']
list_2 = ['a', 'b', 'b', 'b', 'c']

so in the list above, only items in index 0 is the same while index 1 to 4 in both list are different. also, list_2 has an extra item 'c'. I want to count the number of times the index in both list are different, In this case I should get 3.

I tried doing this:

x = 0
for i in max(len(list_1),len(list_2)):
    if list_1[i]==list_2[i]:
        continue
    else:
        x+=1

I am getting an error.

like image 570
jxn Avatar asked Jun 11 '15 21:06

jxn


People also ask

Does order matter compare list Python?

Contrary to lists, sets in Python don't care about order. For example, a set {1, 2, 3} is the same as {2, 3, 1} . As such, we can use this feature to compare the two lists ignoring the elements' order. To do so, we convert each list into a set, then using the == to compare them.

How do I compare two unequal lists in Python?

Compare & get differences between two lists without sets We can iterate over the first list and for each element in that list, check if the second list contains that or not. It will give elements which are present in first list but are missing from second list i.e.

How do you check if two lists are equal without orders?

Using Counter() , we usually are able to get frequency of each element in list, checking for it, for both the list, we can check if two lists are identical or not. But this method also ignores the ordering of the elements in the list and only takes into account the frequency of elements.


2 Answers

Use the zip() function to pair up the lists, counting all the differences, then add the difference in length.

zip() will only iterate over the items that can be paired up, but there is little point in iterating over the remainder; you know those are all to be counted as different:

differences = sum(a != b for a, b in zip(list_1, list_2))
differences += abs(len(list_1) - len(list_2))

The sum() sums up True and False values; this works because Python's boolean type is a subclass of int and False equals 0, True equals 1. Thus, for each differing pair of elements, the True values produced by the != tests add up as 1s.

Demo:

>>> list_1 = ['a', 'a', 'a', 'b']
>>> list_2 = ['a', 'b', 'b', 'b', 'c']
>>> sum(a != b for a, b in zip(list_1, list_2))
2
>>> abs(len(list_1) - len(list_2))
1
>>> difference = sum(a != b for a, b in zip(list_1, list_2))
>>> difference += abs(len(list_1) - len(list_2))
>>> difference
3
like image 102
Martijn Pieters Avatar answered Oct 28 '22 20:10

Martijn Pieters


You can try with this :

list1 = [1,2,3,5,7,8,23,24,25,32]
list2 = [5,3,4,21,201,51,4,5,9,12,32,23]

list3 = []

for i in range(len(list2)):
    if list2[i] not in list1:
        pass
    else :
        list3.append(list2[i])
print list3
print len(list3)
like image 24
Mcmilan Avatar answered Oct 28 '22 19:10

Mcmilan