Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Simple and useful overview. I find enumerate() quite useful. I should probably define generators more often.

One built-in function I basically never use is zip(). I know how it's used and what it does, and I grok the names/ages types of examples that are always used to explain it. But I've simply never needed it in real code. Anyone else use it often, and in what contexts?



I sometimes use zip as a poor man's matrix transposition operator:

    >>> m = [(1,2,3), (4,5,6), (7,8,9)]
    >>> zip(*m)
    [(1, 4, 7), (2, 5, 8), (3, 6, 9)]


If you want to transpose a matrix-like list of lists, but the sizes don't all match up, you can use izip_longest from itertools and give it a fillvalue to "fill in" for the missing elements:

  >>> m = [(1,2,3), (4,5,6), (7, 8)]
  >>> zip(*m)
  [(1, 4, 7), (2, 5, 8)] # Wrong
  >>> from itertools import izip_longest
  >>> list(izip_longest(*m, fillvalue=None))
  [(1, 4, 7), (2, 5, 8), (3, 6, None)]


That's pretty.


Quickly make a dict:

    >>> keys = ["foo", "bar", "spam", "egg"]
    >>> values = [1, 2, 3, 4]
    >>> dict(zip(keys, values))
    {'egg': 4, 'foo': 1, 'bar': 2, 'spam': 3}
Quite useful when you MGET from Redis.


I use it rarely in Python, although it's sometimes useful. I use it more often in other languages to replicate Python's enumerate, since zip(range(len(seq)),seq) is basically enumerate(seq) (although with this implementation it's not a generator).


Ah, but this is:

  from itertools import izip
  izip(xrange(len(seq)), seq)


And in Python 3 it's a generator with

    zip(range(len(seq)), seq)


i use it all the time. mostly to loop over n things at the same time:

   for a, b in zip(list_a, list_b):
      print a + b


For example, trying to solve this problem (CodeJam 2008 minimum scalar product):

You are given two vectors v1=(x1,x2,...,xn) and v2=(y1,y2,...,yn). The scalar product of these vectors is a single number, calculated as x1y1+x2y2+...+xnyn.

Haskell:

  sum(zipWith (*) [1,2,3][3,2,1])
Python is not inherently functional, just supports a few convenience idioms. It has zip, but no zipWith. As a result you have to use list comprehension to perform the same:

  sum([x*y for (x,y) in zip([1,2,3][3,2,1])])


You can use map with several iterables:

  sum(map(operator.mul, [1,2,3], [3,2,1]))


I've used zip before to find an LCA:

    def lca(a,b)
      a.ancestors.zip(b.ancestors).take_while { |a,b| a == b }.last
    end




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: