Q:

Python - Comparing strings and returning Booleans if they are equal

I want to do a function in python that takes 2 strings, and compare the positions. In case they are equal ('a' == 'a') it appends to a list True, and if it's not False. Also if there are more positions in a list, it should return False too.
def g22(S1, S2):
    new = []
    if len(S1) > len(S2):
        for i in range(len(S1)):
            if S1[i] == S2[i]:
                new.append(True)
            elif S1[i] != S2[i]:
                new.append(False)
            else:
                new.append(False)
    elif len(S1) < len(S2):
         for i in range(len(S1)):
            if S1[i] == S2[i]:
                new.append(True)
            elif S1[i] != S2[i]:
                new.append(False)
            else:
                new.append(False)

    return new

This is what i've came up with, but besides thinking it's wrong it's also sloppy.. ideas? Thanks

A:

You can use itertools.zip_longest:
from itertools import zip_longest

def agrees(s,t):
    return [x == y for x,y in zip_longest(s,t)]

For example,
>>> agrees("mathematical", "mythical")
[True, False, True, True, False, False, True, False, False, False, False, False]

Note that zip_longest is izip_longest in Python 2.

A:

Two basic suggestions:

The whole
    if S1[i] == S2[i]:
        new.append(True)
    elif S1[i] != S2[i]:
        new.append(False)
    else:
        new.append(False)

can be replaced with
        new.append(S1[i] == S2[i])

Instead of comparing the two lengths with an if, you could use min(len(S1), len(S2)). This will also fix your current problem of not handling the case when the two lengths match.

Two more advanced suggestions:

You could use a list comprehension instead of an explicit loop.
You could use zip() or map() to simultaneously iterate over the two lists.

A:

Answer without using zip (as per OP's request):
def g22(S1, S2):

    str_max = S1 if len(S1) >= len(S2) else S2
    str_min = S1 if len(S1) < len(S2) else S2

    new = [False]*(len(str_max) - len(str_min))
    new = [str_min[i] == str_max[i] for i in range(len(str_min))] + new
    return new

Hopefully range can be used!

