3

Say I have list1 = [1,2,3,4] and list2 = [5,6,7,8]. How would I compare the first element, 1, in list1 with the first element, 5, in list2? And 2 with 6, 3 with 7, and so on.

I'm trying to use a for loop for this, but I'm not sure how to do it. I understand that doing for x in list1 just checks an element x to all elements in list1, but I don't know how to do it when comparing two lists the way I described.

JS.
16.4k13 gold badges67 silver badges79 bronze badges
asked Dec 7, 2010 at 22:30
1
  • What kind of a comparison result are you looking for and if it's a sequence, what exactly would the possible value of each item be? Commented Dec 8, 2010 at 2:29

3 Answers 3

8

You can traverse both lists simultaneously using zip:

for (x, y) in zip(list1, list2): do_something

The 'zip' function gives you [(1,5), (2,6), (3,7), (4,8)], so in loop iteration N you get the Nth element of each list.

answered Dec 7, 2010 at 22:33
5

The default comparison operators compare lists in lexicographical order. So you can say things like:

>>> [1, 2, 3, 4] < [5, 6, 7, 8]
True

If instead you want to compute the elementwise comparison, you can use map and cmp (or any other operator:

>>> map(cmp, [1, 2, 3, 4], [5, 6, 7, 8])
[-1, -1, -1, -1]
answered Dec 7, 2010 at 22:40
1

If your result is going to be a new list, then you can use a list comprehension:

new_list = [ some_function(i, j) for i, j in zip(list1, list2) ]

Here's a real example of the above code:

>>> list1 = [1, 2, 3, 4]
>>> list2 = [1, 3, 4, 4]
>>> like_nums = [ i == j for i, j in zip(list1, list2) ]
>>> print like_nums
[True, False, False, True]

This will make a list of bools that show whether items of the same index in two lists are equal to each other.

Furthermore, if you use the zip function, there is a way to unzip the result when you are done operating on it. Here's how:

>>> list1 = [1, 2, 3, 4]
>>> list2 = [1, 3, 4, 4]
>>> new_list = zip(list1, list2) # zip
>>> print new_list
[(1, 1), (2, 3), (3, 4), (4, 4)]
>>> newlist1, newlist2 = zip(*new_list) # unzip
>>> print list(newlist1)
[1, 2, 3, 4]
>>> print list(newlist2)
[1, 3, 4, 5]

This could be useful if you need to modify the original lists, while also comparing the elements of the same index in some way.

answered Dec 8, 2010 at 0:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.