python,list,loops,for-loop,indexing , python compare items in 2 list of different length - order is important

## Question:

Tag: python,list,loops,for-loop,indexing
``````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.

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 `1`s.

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
``````

# Related:

## Python: can't access newly defined environment variables

python,bash,environment-variables
I can't access my env var: import subprocess, os print os.environ.get('PATH') # Works well print os.environ.get('BONSAI') # doesn't work But the env var is well added in my /home/me/.bashrc: BONSAI=/home/me/Utils/bonsai_v3.2 export BONSAI And I can access this env var from a new terminal....