3

I am doing a problem, the input is strings:

["abc","bcd","acef","xyz","az","ba","a","z"]

The code is listed below.

def groupStrings(self, strings):
    groups = collections.defaultdict(list)
    for s in strings:
        tmp=[0]*len(s)
        for i in range(len(s)):
            tmp[i]=(ord(s[i])-ord(s[0]))%26
            tmptuple=tuple(tmp)

        groups[tmptuple] += s,
    return groups.values()

So in groups[tmptuple]+=s,

if I remove the comma ',' I get

[["a","b","c","b","c","d","x","y","z"],["a","c","e","f"],["a","z"],["a","z","b","a"]]

instead of

[["abc","bcd","xyz"],["acef"],["a","z"],["az","ba"]]

The groups just does not add the whole string s, can anyone explain why does the comma make it different and why I could not do it without the comma?

miken32
  • 42,008
  • 16
  • 111
  • 154
Andy Young
  • 31
  • 1

1 Answers1

8

The trailing comma makes a tuple, with a single element, s. Python doesn't require parentheses to make a tuple unless there is ambiguity (e.g. with function call parens); aside from the empty tuple (()), you can usually make tuples with just commas, no parentheses at all. In this case, a single trailing comma, s,, is equivalent to (s,).

Since groups has list values, this means that doing += s, is equivalent to .append(s) (technically, it's closer to .extend((s,)), but the end result is the same). Someone is probably trying to save a few keystrokes.

If you omitted the comma, it would be doing list += str, interpreting the str as a sequence of characters and extending the list with each of the resulting len 1 strings, as you observed.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271