Printing n elements per line in a list

Sion Arrowsmith siona at chiark.greenend.org.uk
Wed Aug 16 07:57:02 EDT 2006


In article <m21wrh4ily.fsf at unique.fqdn>, Dan Sommers  <me at privacy.net> wrote:
>Perhaps not the prettiest, but I can't think of anything simpler to read
>six months from now:
>
>    counter = 0
>    for an_element in the_list:
>        print an_element,
>        counter = counter + 1
>        if counter == n:
>            print
>            counter = 0

for counter, an_element in enumerate(the_list):
    print an_element,
    if not (counter+1) % n:
        print
# Plus the final print fixed in an earlier follow-up:
if len(the_list) % n:
    print

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |    -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list