# Streamlined for-loop for comparing two lists

I'm new to Python and I'm wondering is there a way to streamline this clunky code I've written. Maybe a built-in function I've never come across before?

I run through two lists of binary numbers and if the same number appears at the same index in list one and two, do x.

So in the example below the number 1 appears at index 2 in both lists.

list1 = [0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
list2 = [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0]

for position, binary in enumerate(list1):
for placement, number in enumerate(list2):
if position == placement and binary == 1 and binary == number:
do x

-

Your solution's time complexity is O(n2), which is far from optimal. Your lists contain 19 elements - so your solution performs an order of 361 operations. In order to get a linear solution, you can simulate a "-style" for loop using range:

for i in range(len(list1)): # assuming the lists are of the same length
if list1[i]==list2[i]:
do x


Now the loop runs exactly 19 times - much better!

Another thing: your code checks if binary==1. Is it what you want? If so, Python's equal operator can operate on three arguments, making it more readable:

for i in range(len(list1)): # assuming the lists are of the same length
if list1[i]==list2[i]==1:
do x


Lastly, you may want to represent a binary number using the most natural way - as a number. Aside from space consideration, most languages (including Python) have standard binary (often called bitwise) operations.

-
It probably is what he wants.. Looks like he's ANDing everything. –  Millie Smith Mar 12 '14 at 17:07
Yeah, but the description says "same number". –  Benesh Mar 12 '14 at 17:10
Good point. I missed that. –  Millie Smith Mar 12 '14 at 17:11
Thanks for the great explanation! –  AnonyMouse Mar 12 '14 at 21:12

Python has a neat built in called 'zip' which creates a pairwise list from multiple iterables. So you could do:

pairwise = zip (list1, list2)
matched_digits = [idx for idx, pair in enumerate(pairwise) if pair[0] == pair[1]]


Which zips up the list and returns the indices of all the pairs which match

-
I love zip, thanks for bringing it forth –  Claudiordgz Mar 12 '14 at 20:56
for i,j in zip (list1, list2):