printing list

C

compboy

How do you print elements of the list in one line?

alist = [1, 2, 5, 10, 15]

so it will be like this:
1, 2, 5, 10, 15

because if I use this code

for i in alist:
print i

the result would be like this

1
2
5
10
15

Thanks.
 
G

Gary Herron

compboy said:
How do you print elements of the list in one line?

alist = [1, 2, 5, 10, 15]

so it will be like this:
1, 2, 5, 10, 15

because if I use this code

for i in alist:
print i

the result would be like this

1
2
5
10
15

Thanks.

Well, first, if you just print alist you'll get

[1, 2, 5, 10, 15]

which may be good enough. If that's not what you want then you can suppress the automatic RETURN that follows a print's output by adding a trailing comma to the print statement, like this

for i in alist:
print i,

1 2 5 10 15

Gary Herron
 
T

Tim Chase

compboy said:
How do you print elements of the list in one line?

alist = [1, 2, 5, 10, 15]

so it will be like this:
1, 2, 5, 10, 15
1, 2, 5, 10, 15

-tkc
 
R

Raymond L. Buvel

compboy said:
How do you print elements of the list in one line?

alist = [1, 2, 5, 10, 15]

so it will be like this:
1, 2, 5, 10, 15

because if I use this code

for i in alist:
print i

the result would be like this

1
2
5
10
15

Thanks.

There are a number of ways to do it but if you want a one-liner:

print repr(alist)[1:-1]

will meet your spec.
 
M

Mel Wilson

Tim said:
compboy said:
How do you print elements of the list in one line?

alist = [1, 2, 5, 10, 15]

so it will be like this:
1, 2, 5, 10, 15
print ', '.join(alist)
1, 2, 5, 10, 15

???

Python 2.4.2 (#1, Jan 23 2006, 21:24:54)
[GCC 3.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>> a=[1,2,3,4,5]
>>> print ', '.join (a)
Traceback (most recent call last):
1, 2, 3, 4, 5
 
D

Dan Sommers

Tim said:
compboy said:
How do you print elements of the list in one line?

alist = [1, 2, 5, 10, 15]

so it will be like this:
1, 2, 5, 10, 15

print ', '.join(alist) 1, 2, 5, 10, 15
???

Python 2.4.2 (#1, Jan 23 2006, 21:24:54)
[GCC 3.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
a=[1,2,3,4,5]
print ', '.join (a)
Traceback (most recent call last):
1, 2, 3, 4, 5

Or one of:

print ', '.join(str(x) for x in a)

print ', '.join(map(str, a))

both of which work if the list contains non-integer elements.

Regards,
Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,794
Messages
2,569,641
Members
45,353
Latest member
RogerDoger

Latest Threads

Top