473,773 Members | 2,269 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Printing n elements per line in a list

If have a list from 1 to 100, what's the easiest, most elegant way to
print them out, so that there are only n elements per line.

So if n=5, the printed list would look like:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
etc.

My search through the previous posts yields methods to print all the
values of the list on a single line, but that's not what I want. I feel
like there is an easy, pretty way to do this. I think it's possible to
hack it up using while loops and some ugly slicing, but hopefully I'm
missing something

Aug 15 '06 #1
26 17960
"unexpected " <su***********@ gmail.comwrites :
If have a list from 1 to 100, what's the easiest, most elegant way to
print them out, so that there are only n elements per line.

So if n=5, the printed list would look like:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
etc.

My search through the previous posts yields methods to print all the
values of the list on a single line, but that's not what I want. I feel
like there is an easy, pretty way to do this. I think it's possible to
hack it up using while loops and some ugly slicing, but hopefully I'm
missing something
The most direct way would be something like (untested):

for i in xrange(0, 100, 5):
print ' '.join(str(j) for j in a[i:i+5])

where a is the array. If you prefer a "coordinate-free" style, you
could use something like:

for x,y in itertools.group by(a, lambda n: n//5):
print ' '.join(str(k) for k in y)

I hope I got that right.
Aug 16 '06 #2
Paul Rubin <http://ph****@NOSPAM.i nvalidwrites:
for x,y in itertools.group by(a, lambda n: n//5):
print ' '.join(str(k) for k in y)

I hope I got that right.
Of course I meant to say
for x,y in itertools.group by(enumerate(a) , lambda (n,x): n//5):
print ' '.join(str(k) for n,k in y)
This is still way ugly and I've never found a really good solution.
Aug 16 '06 #3
On 15 Aug 2006 16:51:29 -0700,
"unexpected " <su***********@ gmail.comwrote:
If have a list from 1 to 100, what's the easiest, most elegant way to
print them out, so that there are only n elements per line.
So if n=5, the printed list would look like:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
etc.
My search through the previous posts yields methods to print all the
values of the list on a single line, but that's not what I want. I feel
like there is an easy, pretty way to do this. I think it's possible to
hack it up using while loops and some ugly slicing, but hopefully I'm
missing something
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

Regards,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
"I wish people would die in alphabetical order." -- My wife, the genealogist
Aug 16 '06 #4
unexpected wrote:
If have a list from 1 to 100, what's the easiest, most elegant way to
print them out, so that there are only n elements per line.

So if n=5, the printed list would look like:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
etc.

My search through the previous posts yields methods to print all the
values of the list on a single line, but that's not what I want. I feel
like there is an easy, pretty way to do this. I think it's possible to
hack it up using while loops and some ugly slicing, but hopefully I'm
missing something
>From http://docs.python.org/lib/itertools-recipes.html there's the
grouper() function:

from itertools import izip, chain, repeat

def grouper(n, iterable, padvalue=None):
"""
Return n-tuples from iterable, padding with padvalue.
Example:
grouper(3, 'abcdefg', 'x') -->
('a','b','c'), ('d','e','f'), ('g','x','x')
"""
return izip(*[chain(iterable, repeat(padvalue , n-1))]*n)

R = range(1, 101)

for N in grouper(5, R, ''):
print ' '.join(str(n) for n in N)

If your iterable is not a multiple of n (of course not the case for 100
and 5), and you don't want the extra spaces at the end of your last
line, you could join the lines with '\n' and stick a call to rstrip()
in there:

G = grouper(5, R, '')
print '\n'.join(' '.join(str(n) for n in N) for N in G).rstrip()

but then you're back to ugly. lol.

Peace,
~Simon

Aug 16 '06 #5

Dan Sommers wrote:
>
counter = 0
for an_element in the_list:
print an_element,
counter = counter + 1
if counter == n:
print
counter = 0
Yes, often simple old-fashioned ways are the best. A little verbose,
though. And I'd do some old-fashioned testing -- the above needs "if
counter: print" after the loop has finished, to get the final '\n' for
cases where there are not an even multiple of n elements.
>>def wrapn(alist, n):
.... ctr = 0
.... for item in alist:
.... print item,
.... ctr = (ctr + 1) % n
.... if not ctr:
.... print
.... if ctr:
.... print
....
>>for k in range(8):
.... print '--- %d ---' % k
.... wrapn(range(k), 3)
....
--- 0 ---
--- 1 ---
0
--- 2 ---
0 1
--- 3 ---
0 1 2
--- 4 ---
0 1 2
3
--- 5 ---
0 1 2
3 4
--- 6 ---
0 1 2
3 4 5
--- 7 ---
0 1 2
3 4 5
6
>>>
Cheers,
John

Aug 16 '06 #6
On Tue, 15 Aug 2006 16:51:29 -0700, unexpected wrote:
If have a list from 1 to 100, what's the easiest, most elegant way to
print them out, so that there are only n elements per line.

So if n=5, the printed list would look like:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
etc.

My search through the previous posts yields methods to print all the
values of the list on a single line, but that's not what I want. I feel
like there is an easy, pretty way to do this. I think it's possible to
hack it up using while loops and some ugly slicing, but hopefully I'm
missing something
I don't see why you think that's an ugly hack.

def printitems(sequ ence, count=5):
"""Print count items of sequence per line."""
numrows = len(sequence)//count
if len(sequence)%c ount != 0: numrows += 1
for start in range(0, numrows):
items = sequence[start*count:(st art+1)*count]
for item in items:
print item,
print

--
Steven D'Aprano

Aug 16 '06 #7

Steven D'Aprano wrote:
I think it's possible to
hack it up using while loops and some ugly slicing, but hopefully I'm
missing something

I don't see why you think that's an ugly hack.

def printitems(sequ ence, count=5):
"""Print count items of sequence per line."""
numrows = len(sequence)//count
if len(sequence)%c ount != 0: numrows += 1
for start in range(0, numrows):
items = sequence[start*count:(st art+1)*count]
for item in items:
print item,
print
Ugliness is in the eye of the beholder.
It is more blessed to add than to multiply.
Gaze upon this alternative:

def printitems2(seq uence, count=5):
"""Print count items of sequence per line."""
for pos in range(0, len(sequence), count):
for item in sequence[pos:pos+count]:
print item,
print

Cheers,
John

Aug 16 '06 #8
John Machin wrote:
Steven D'Aprano wrote:
I think it's possible to
hack it up using while loops and some ugly slicing, but hopefully I'm
missing something
I don't see why you think that's an ugly hack.

def printitems(sequ ence, count=5):
"""Print count items of sequence per line."""
numrows = len(sequence)//count
if len(sequence)%c ount != 0: numrows += 1
for start in range(0, numrows):
items = sequence[start*count:(st art+1)*count]
for item in items:
print item,
print

Ugliness is in the eye of the beholder.
It is more blessed to add than to multiply.
Gaze upon this alternative:

def printitems2(seq uence, count=5):
"""Print count items of sequence per line."""
for pos in range(0, len(sequence), count):
for item in sequence[pos:pos+count]:
print item,
print

Cheers,
John
Very nice.

~Simon

Aug 16 '06 #9
On 15 Aug 2006 18:33:51 -0700,
"John Machin" <sj******@lexic on.netwrote:
Dan Sommers wrote:
>>
counter = 0
for an_element in the_list:
print an_element,
counter = counter + 1
if counter == n:
print
counter = 0
Yes, often simple old-fashioned ways are the best. A little verbose,
though. And I'd do some old-fashioned testing -- the above needs "if
counter: print" after the loop has finished, to get the final '\n' for
cases where there are not an even multiple of n elements.
I know I *thought* "untested"; I could have sworn that I typed it, too.
Sorry.

OTOH, pasted directly from my interactive python session (I changed
sys.ps2 to four spaces to make pasting from these sessions into an
editor that much easier):

Python 2.4.2 (#1, Jun 17 2006, 00:09:19)
[GCC 4.0.1 (Apple Computer, Inc. build 5247)] on darwin
Type "help", "copyright" , "credits" or "license" for more information.
>>c = 0
for e in range(10):
print e,
c = c + 1
if c == 3:
print
c = 0

0 1 2
3 4 5
6 7 8
9
>>>
And pasted right from an xterm:

$ python -c 'print 3,'
3
$

(All of which only explains your more complex test harness, and I still
should have looked more carefully before I posted.)
... ctr = (ctr + 1) % n
I'm old enough to remember the days when we avoided division like the
plague. Remember those zippy 1MHz (yes, that's an M and not a G) CPUs
with less than a handful of 8-bit registers? Old habits die hard. ;-)

Regards,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
"I wish people would die in alphabetical order." -- My wife, the genealogist
Aug 16 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
1880
by: beliavsky | last post by:
To print a list with a specified format one can write (for example) for j in : print "%6d"%j, print The code print "%6d"%
12
6739
by: Stanimir Stamenkov | last post by:
Here are two cases regarding inline-level elements' line-height, padding and background, which I doesn't understand: <div style="background: black; color: white; line-height: 1.5"> <span>Abc</span> <span style="background: white; color: black; line-height: 3">Abc</span> <span>Abc</span> </div>
12
2330
by: Tescobar | last post by:
Over one year ago somebody asked here: how to remove selected elements from list in a loop?. The answer was as follows: for( it = l.begin(); it != l.end; ) { if(...) it = l.erase(it); else ++it;
5
1812
by: micklee74 | last post by:
hi i have a list with contents like this alist = how can i "convert" this list into a dictionary such that dictionary = { '>QWER':'askfhs' , '>REWR' : 'sfsdf' , '>FGDG', 'sdfsdgffdgfdg' }
13
2084
by: cz | last post by:
Hi there, I'm sure there is a very simple solution for my question, I just didn't find it up to now. I'm using a badly documented module and therefore need to find out about how to access the elements in a list. (I need to do this in Python 1.5.3) Any help appreciated very much. Thanks! cz
3
2987
by: Muhammad Ahsin Saleem | last post by:
Hi I want to make a multi Line List Box. This list box will have multiple lines for one item and this list box have all other functions like the single line list box. Can any body help me its urgant
6
10372
by: Tekkaman | last post by:
I have a list of lists and I want to define an iterator (let's call that uniter) over all unique elements, in any order. For example, calling: sorted(uniter(, , ])) must return . I tried the following implementations: from itertools import chain
4
3178
by: Bob | last post by:
Is there a faster way to add the array elements to a list then looping through the elements like: double toadd; list<doublelistwant; for (int i=0;i<toadd.Length;i++){ listwant.Add(toadd);
11
28519
by: patelxxx | last post by:
When I running the following .cgi script, not sure why each print statement is not printing on a new line, even after entering \n. Browser=IE6 See Perl code below: #!C:/perl/bin/perl.exe -w print "Content-type:text/html\n\n"; use CGI qw(:standard);
2
3275
by: antar2 | last post by:
Hello, I am a beginner in python. following program prints the second element in list of lists 4 for the first elements in list 4 that are common with the elements in list 5 list4 = ,,] list5 =
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8937
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7463
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6717
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5355
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4012
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2852
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.