0
    char_set = [False for _ in range(128)]
    for char in string:
       val = ord(char)
       if char_set[val]:
           # Char already found in string
           return False
       char_set[val] = True

I'm trying to decipher this code but don't understand what char_set is doing? The part inside the list is confusing.

  • Note: When initializing a `list` of the same immutable object many times over, it's faster/simpler to do `char_set = [False] * 128`. Key point: Only do this for `list`s of _immutable_ objects (`bool`, numerics, `tuple`, `frozenset`, `str`, `bytes`, what have you), don't do it for mutable objects because you'll end up with a bunch of references to the same mutable object, which is rarely what you want (changing one changes all of them). – ShadowRanger Nov 19 '16 at 03:57

1 Answers1

1

[False for _ in range(128)] is a list comprehension that will return a list of 128 Falses. In other words, char_set will be [False, False, ...] with 128 False. The _ represents a throwaway value (a value which is created by the range() function, but that the program does not need to do anything with. In this case, _ is the number representing the iterations of the range() function (i.e., 0, 1, 2, etc.).

elethan
  • 16,408
  • 8
  • 64
  • 87