How to compare two lists in python

list, numpy, python, python-3.x, python-itertools

Solution

Answering both parts with `zip` and `all`

all(i < j for (i, j) in zip(a, b))

`zip` will pair the values from the beginning of `a` with values from beginning of `b`; the iteration ends when the shorter iterable has run out. `all` returns `True` if and only if all items in a given are true in boolean context. Also, when any item fails, `False` will be returned early.

Example results:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> all(i < j for (i, j) in zip(a, b))
True
>>> a = [1,2,7]
>>> b = [4,5,6]
>>> all(i < j for (i, j) in zip(a, b))
False
>>> a = [1,2]
>>> b = [4,5,-10]
>>> all(i < j for (i, j) in zip(a, b))
True

Timings with IPython 3.4.2:

In [1]: a = [1] * 10000
In [2]: b = [1] * 10000
In [3]: %timeit all(i < j for (i, j) in zip(a, b))
1000 loops, best of 3: 995 µs per loop
In [4]: %timeit all(starmap(lt, zip(a, b)))
1000 loops, best of 3: 487 µs per loop

So the starmap is faster in this case. In general 2 things are relatively slow in Python: function calls and global name lookups. The `starmap` of Retard's solution seems to win here exactly because the tuple yielded from `zip` can be fed as-is as the *args to the `lt` builtin function, whereas my code needs to deconstruct it.

Problem

Suppose I have two lists (or `numpy.array`s): ``` a = [1,2,3] b = [4,5,6] ``` How can I check if each element of `a` is smaller than corresponding element of `b` at the same index? (I am assuming indices are starting from 0) i.e. ``` at index 0 value of a = 1 < value of b = 4 at index 1 value of a = 2 < value of b = 5 at index 2 value of a = 3 < value of b = 6 ``` If `a` were equal to `[1,2,7]`, then that would be incorrect because at index 2 value of `a` is greater than that of `b`. Also if `a`'s length were any smaller than that of `b`, it should be comparing only the indices of `a` with those of `b`. For example this pair `a`, `b` ``` a = [1,2] b = [3,4,5] ``` at indices 0 and 1, value of `a` is smaller than `b`, thus this would also pass the check. P.S.--> I have to use the above conditions inside a `if` statement. And also, no element of `a` should be equal to that of `b` i.e. strictly lesser. Feel free to use as many as tools as you like. (Although I am using lists here, you can convert the above lists into numpy arrays too.)

Original source