6 Matching Annotations
  1. Feb 2016
    1. The rule of thumb is to avoid using more than two expressions in a list comprehension. This could be two conditions, two loops, or one condition and one loop. As soon as it gets more complicated than that, you should use normal if and for statements and write a helper function
    2. Dictionaries and sets have their own equivalents of list comprehen-sions.

      It gets better an better!

      d = { "foo": "bar", "baz": "qux" }
      r = {val: key for key, val in d.items()}
      #=> { "bar": "foo", "qux": "baz" }
      
    3. Unlike map, list comprehensions let you easily filter items from the input list, removing corresponding outputs from the result.

      This might be the greatest advantage of list comprehensions. Even in Ruby requires one to return a nil value from a map and then a call to compact, like: array.map(&:transform).compact.

    4. Beware that indexing a list by a negative variable is one of the few situations in which you can get surprising results from slicing. For example, the expression so melist[-n:] will work fine when n is greater than one (e.g., somelist[-3:]). However, when n is zero, the expression so melist[-0:] will result in a copy of the original list.

      Which is the same for somelist[:]. Not sure what the author is getting at. Maybe he meant to say that using variables as indexes when slicing can become confusing?

    5. Slicing can be extended to any Python class that implements the__getitem__ and __setitem__ special methods
    6. In a file, functions and classes should be separated by two blank lines.

      I wonder what the reasoning for having two blank lines for separating functions and one blank line for methods is. Seems like an arbitrary distinction.