Skip to content

Instantly share code, notes, and snippets.

@kevinjqiu
Last active January 26, 2016 02:27
Show Gist options
  • Save kevinjqiu/98d2f3a7c35be7332d8f to your computer and use it in GitHub Desktop.
Save kevinjqiu/98d2f3a7c35be7332d8f to your computer and use it in GitHub Desktop.
Fluent Python Notes

Chapter 2 An Array of Sequences

list comprehension no longer leaks variables

use * in tuple unpacking.

This can be used to facilitate car, cdr:

head, *tail = lst

Too bad this is Python 3 only...

Tuple-unpacking is one of my favourite Python features

Simplified version of pattern matching that's in Erlang or Scala, yet the most useful one.

A[thing] invokes __getitem__

and thing can be anything! Good for implementing magic.

class A(object):
    def __getitem__(self, idx):
        print idx

A()[1:0, 2:0]
# (slice(1, 0, None), slice(2, 0, None))

A tuple of two slice objects.

deque

  • thread-safe double-ended queue for fast inserting and removing from both ends.
  • maxlen to implement a list of 'last seen' elements

Chapter 3 Dictionaries and Sets

All immutable objects are hashable, except for tuple

Consider:

>>> frozenset([1,2,[]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  TypeError: unhashable type: 'list'

>>> tuple([1,2,[]])
(1, 2, [])

collections.ChainMap

collections.Counter implementation of a frequently-used idiom

Prefer set literal than set() constructor

To save a few byte code instructions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment