Virgil Stokes wrote: >>> def testFunc(startingList): >>>xOnlyList = []; j = -1 >>>for xl in startingList: >>>if (xl[0] == 'x'): >> That's going to fail in the starting list contains an empty string. Use >> xl.startswith('x') instead. > Yes, but this was by design (tacitly assumed that startingList was both a > list and non-empty).
You missunderstood it will fail if the list contains an empty string, not if the list itself is empty: >>> words = ["alpha", "", "xgamma"] >>> [word for word in words if word[0] == "x"] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range The startswith() version: >>> [word for word in words if word.startswith("x")] ['xgamma'] Also possible: >>> [word for word in words if word[:1] == "x"] ['xgamma'] > def testFunc1(startingList): > ''' > Algorithm-1 > Note: > One should check for an empty startingList before > calling testFunc1 -- If this possibility exists! > ''' > return([x for x in startingList if x[0] == 'x'], > [x for x in startingList if x[0] != 'x']) > > > I would be interested in seeing code that is faster than algorithm-1 In pure Python? Perhaps the messy variant: def test_func(words): nox = [] append = nox.append withx = [x for x in words if x[0] == 'x' or append(x)] return withx, nox -- http://mail.python.org/mailman/listinfo/python-list