Muffinresearch Labs by Stuart Colville

Python: Transposing Lists With map and zip | 6 Comments

Posted in Code on 16th October 2007, 11:05 am by

I’m re-writing a piece of code to print into columns within a terminal and I wanted to join the nth items of each list together. Zip allows you to do just that

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

But truncates the output to the shortest common length.

I then stumbled across this snippet about map in the manual:

map( function, list, …)
Apply function to every item of list and return a list of the results. If additional list arguments are passed, function must take that many arguments and is applied to the items of all lists in parallel; if a list is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple list arguments, map() returns a list consisting of tuples containing the corresponding items from all lists (a kind of transpose operation). The list arguments may be any kind of sequence; the result is always a list.

In other words is the function is None the resulting tuples are padded with None

>>> my_list=[[1,2,3],[4,5,6],[7,8,9,10]]
>>> print map(None,*my_list)
[(1, 4, 7), (2, 5, 8), (3, 6, 9), (None, None, 10)]

Now in-case you are looking at this wondering what the star (*) syntax is, it is called an “Arbitrary Argument List” and it’s useful here as it expands our list to pass each of the lists within the outer list as an arguments to zip and map.

Post Tools

  • http://my.opera.com/raphman Raphael

    Great. Thanks!

  • Pingback: Batteries included has strong resonance « Yet another blog again

  • wearetherock

    Cool, Arbitrary Argument List is new knowledge for me.

  • gaul1

    Tnx a lot for helping me with
    >zip(* list)

  • Wes

    Very confusing (at best, misleading at worst) to rebind the builtin list! Use another variable name.

  • http://muffinresearch.co.uk Stuart Colville

    Yep good point, I’ve used a different var name

GNU screen: open tab in current working directory|(1)

A nice trick for having screen open a new tab in the same directory as the one you’re currently in. To use it add it to your .screenrc

# Open new window in current dir.
bind c stuff "screen -X chdir \$PWD;screen^M"
bind ^c stuff "screen -X chdir \$PWD;screen^M"

Hat tip: mteckert on SuperUser.com

Ubuntu: add-apt-repository: command not found|(3)

When you’re using a minimal Ubuntu install if you find the ‘add-apt-repository’ command is missing (it’s useful for adding PPAs and other repositories), then simply run:

sudo apt-get install python-software-properties

Photos on Flickr

© Copyright 2004-12 Stuart Colville, all rights reserved. May contain traces of Muffin. Powered by WordPress. Hosting by Slicehost.com This page was baked in 0.511s.