list comparison vs integer comparison, which is more efficient?

Chris Angelico rosuav at gmail.com
Sat Jan 3 18:40:07 EST 2015


On Sun, Jan 4, 2015 at 10:19 AM, austin aigbe <eshikafe at gmail.com> wrote:
> I would like to know which is more efficient to use, between an integer comparison and a list comparison:

You can test them with the timeit module, but my personal suspicion is
that any difference between them will be utterly and completely
dwarfed by all your sqrt(2) calls in the complex constructors. If you
break those out, and use a tuple instead of a list, you could write
this very simply and tidily:

    bits = {
        (0,0): complex(1/math.sqrt(2),1/math.sqrt(2)),
        (0,1): complex(1/math.sqrt(2),-1/math.sqrt(2)),
        (1,0): complex(-1/math.sqrt(2),1/math.sqrt(2)),
        (1,1): complex(-1/math.sqrt(2),-1/math.sqrt(2)),
    }
    # QPSK - TS 36.211 V12.2.0, section 7.1.2, Table 7.1.2-1
    def mp_qpsk(self):
        r = []
        for i in range(self.nbits/2):
            bit_pair = self.sbits[i*2:i*2+2]
            r.append(bits[tuple(bit_pair)])
        return r

At this point, your loop looks very much like a list comprehension in
full form, so you can make a simple conversion:

# From itertools recipes
# https://docs.python.org/3/library/itertools.html
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)
# Replace zip() with izip() for the Python 2 equivalent.

    def mp_qpsk(self):
        return [bits[pair] for pair in pairwise(self.sbits)]

How's that look? I don't care if it's faster or not, I prefer this form :)

ChrisA



More information about the Python-list mailing list