How to print a list more nicely?

This answer uses the same method in the answer by @Aaron Digulla, with slightly more pythonic syntax. It might make some of the above answers easier to understand.

>>> for a,b,c in zip(foolist[::3],foolist[1::3],foolist[2::3]):
>>>     print '{:<30}{:<30}{:<}'.format(a,b,c)

exiv2-devel                   mingw-libs                    tcltk-demos
fcgi                          netcdf                        pdcurses-devel
msvcrt                        gdal-grass                    iconv
qgis-devel                    qgis1.1                       php_mapscript

This can be easily adapt to any number of columns or variable columns, which would lead to something like the answer by @gnibbler. The spacing can be adjusted for screen width.


Update: Explanation as requested.

Indexing

foolist[::3] selects every third element of foolist. foolist[1::3] selects every third element, starting at the second element (‘1’ because python uses zero-indexing).

In [2]: bar = [1,2,3,4,5,6,7,8,9]
In [3]: bar[::3]
Out[3]: [1, 4, 7]

zip

Zipping lists (or other iterables) generates tuples of the elements of the the lists. For example:

In [5]: zip([1,2,3],['a','b','c'],['x','y','z'])
Out[5]: [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z')]

together

Putting these ideas together we get our solution:

for a,b,c in zip(foolist[::3],foolist[1::3],foolist[2::3]):

Here we first generate three “slices” of foolist, each indexed by every-third-element and offset by one. Individually they each contain only a third of the list. Now when we zip these slices and iterate, each iteration gives us three elements of foolist.

Which is what we wanted:

In [11]: for a,b,c in zip(foolist[::3],foolist[1::3],foolist[2::3]):
   ....:      print a,b,c                           
Out[11]: exiv2-devel mingw-libs tcltk-demos
         fcgi netcdf pdcurses-devel
        [etc]

Instead of:

In [12]: for a in foolist: 
   ....:     print a
Out[12]: exiv2-devel
         mingw-libs
         [etc]

Leave a Comment