473,387 Members | 1,891 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Is there a commas-in-between idiom?

Hi experts,

it's very common that I have a list and I want to print it with commas
in between. How do I do this in an easy manner, whithout having the
annoying comma in the end?

<code>

list = [1,2,3,4,5,6]

# the easy way
for element in list:
print element, ',',

print
# this is what I really want. is there some way better?
if (len(list) 0):
print list[0],
for element in list[1:]:
print ',', element,

</code>

Thx,
Ernesto
Nov 5 '06 #1
14 1423
Ernesto García García <ti**********************@gmail.comwrites:
Hi experts,

it's very common that I have a list and I want to print it with commas
in between. How do I do this in an easy manner, whithout having the
annoying comma in the end?
>>list = [1,2,3,4,5,6]
print ','.join(map(str, list))
1,2,3,4,5,6

--
Christian Joergensen | Linux, programming or web consultancy
http://www.razor.dk | Visit us at: http://www.gmta.info
Nov 5 '06 #2
Ernesto García García wrote:
it's very common that I have a list and I want to print it with commas
in between. How do I do this in an easy manner, whithout having the
annoying comma in the end?
>>items = [1, 2, 3, "many"]
print ", ".join(str(item) for item in items)
1, 2, 3, many

Peter
Nov 5 '06 #3
Ernesto García García wrote:
Hi experts,

it's very common that I have a list and I want to print it with commas
in between. How do I do this in an easy manner, whithout having the
annoying comma in the end?

<code>

list = [1,2,3,4,5,6]

# the easy way
for element in list:
print element, ',',

print
# this is what I really want. is there some way better?
if (len(list) 0):
print list[0],
for element in list[1:]:
print ',', element,

</code>

Thx,
Ernesto
print ",".joint(some_list)

Where what you have named "list" is now called "some_list" because it is
terribly ill-advised to reassign the name of a built-in type.

James
Nov 5 '06 #4
Ernesto García García wrote:
Hi experts,

it's very common that I have a list and I want to print it with commas
in between. How do I do this in an easy manner, whithout having the
annoying comma in the end?

<code>

list = [1,2,3,4,5,6]

# the easy way
for element in list:
print element, ',',

print
# this is what I really want. is there some way better?
if (len(list) 0):
print list[0],
for element in list[1:]:
print ',', element,

</code>

Thx,
Ernesto
mylist = [1,2,3,4,5,6]
print ','.join(map(str, mylist))

Great solution!

Thank all of you,
Ernesto
Nov 5 '06 #5
]Ernesto García García]
it's very common that I have a list and I want to print it with commas
in between. How do I do this in an easy manner, whithout having the
annoying comma in the end?

<code>

list = [1,2,3,4,5,6]

# the easy way
for element in list:
print element, ',',

print
# this is what I really want. is there some way better?
if (len(list) 0):
More idiomatic as

if len(list) 0:

and even more so as plain

if list:
print list[0],
for element in list[1:]:
print ',', element,
Do you really want a space before and after each inter-element comma?
</code>
An often-overlooked alternative to playing with ",".join() is:

print str(list)[1:-1]

That is, ask Python to change the list into a big string, and just
strip the brackets off each end:
>>alist = ['a, bc', 4, True]
print str(alist)[1:-1]
'a, bc', 4, True

Note the quotes around the string element! This differs from what
your code snippet above would produce (in addition to differing wrt
spaces around inter-element commas):

a, bc , 4 , True
Nov 5 '06 #6
Tim Peters wrote:
More idiomatic as

if len(list) 0:

and even more so as plain

if list:
> print list[0],
for element in list[1:]:
print ',', element,


Do you really want a space before and after each inter-element comma?
No, but it was only an example. I usually go for string concatenation.
An often-overlooked alternative to playing with ",".join() is:

print str(list)[1:-1]
That's funny! Not that I like it more that the join solution, but funny
nevertheless.

Thank you,
Ernesto
Nov 5 '06 #7
Ernesto García García wrote:
it's very common that I have a list and I want to print it with commas
in between. How do I do this in an easy manner, whithout having the
annoying comma in the end?
I've collected a bunch of list pydioms and other notes here:

http://effbot.org/zone/python-list.htm

For formatting issues, see:

http://effbot.org/zone/python-list.htm#printing

</F>

Nov 6 '06 #8
I've collected a bunch of list pydioms and other notes here:
>
http://effbot.org/zone/python-list.htm
Thank you for the suggestion.

Ernesto
Nov 6 '06 #9
On 2006-11-06, Fredrik Lundh <fr*****@pythonware.comwrote:
I've collected a bunch of list pydioms and other notes here:

http://effbot.org/zone/python-list.htm
"""
A = B = [] # both names will point to the same list
"""

I've been bitten by this once or twice in the past, but I have always
wondered what it was useful for? Can anybody enlighten me?

TIA,

PterK

--
Peter van Kampen
pterk -- at -- datatailors.com
Nov 8 '06 #10
Peter van Kampen schrieb:
On 2006-11-06, Fredrik Lundh <fr*****@pythonware.comwrote:
>I've collected a bunch of list pydioms and other notes here:

http://effbot.org/zone/python-list.htm

"""
A = B = [] # both names will point to the same list
"""

I've been bitten by this once or twice in the past, but I have always
wondered what it was useful for? Can anybody enlighten me?
Do you never have a situation where you want to assign the same value
to two variables?

Or are you objecting to the fact that both names point to the same object?
It couldn't be otherwise. Consider:

X = []
A = B = X

What should this do? Copy "X" and assign one copy to A, one to B?

Georg
Nov 8 '06 #11
At Wednesday 8/11/2006 16:51, Peter van Kampen wrote:
>"""
A = B = [] # both names will point to the same list
"""

I've been bitten by this once or twice in the past, but I have always
wondered what it was useful for? Can anybody enlighten me?
As an optimization, inside a method, you can bind an instance
attribute and a local name to the same object:

def some_action(self):
self.items = items = []
// following many references to self.items,
// but using items instead.

Names in the local namespace are resolved at compile time, so using
items is a lot faster than looking for "items" inside self's
namespace each time it's used.
--
Gabriel Genellina
Softlab SRL

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Nov 8 '06 #12
Ernesto García García wrote:
list = [1,2,3,4,5,6]
Just a nit-pick: It's considered an anti-idiom
to hide builtins just as list by using it as a
name for a variable.
>>list=[1,2,3,4,5]
tuple = (1,2,3,4,5)
if list == list(tuple): print "equal"
....
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'list' object is not callable
>>#ouch!
....
>>l=list
del list
if l == list(tuple): print "equal"
....
equal
>>if tuple(l)==tuple: print "equal"
....
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'tuple' object is not callable
>>t=tuple
del tuple
if tuple(l)==t: print "equal"
....
equal
Nov 9 '06 #13
On 2006-11-08, Georg Brandl <g.*************@gmx.netwrote:
Peter van Kampen schrieb:
>On 2006-11-06, Fredrik Lundh <fr*****@pythonware.comwrote:
>>I've collected a bunch of list pydioms and other notes here:

http://effbot.org/zone/python-list.htm

"""
A = B = [] # both names will point to the same list
"""

I've been bitten by this once or twice in the past, but I have always
wondered what it was useful for? Can anybody enlighten me?

Do you never have a situation where you want to assign the same value
to two variables?
In the sense that I might want two empty lists or maybe 2 ints that
are initialised as 0 (zero). That's what I (incorrectly) thought A = B
= [] did.
Or are you objecting to the fact that both names point to the same
object?
I'm not objecting to anything, merely wondering when I could/should
use this idiom. There's a nice example in another response (self.items
= items = [])
It couldn't be otherwise. Consider:

X = []
A = B = X

What should this do? Copy "X" and assign one copy to A, one to B?
Ah yes, I see the error in my ways...I skipped the A = B part too
lightly.

Thanks,

PterK
--
Peter van Kampen
pterk -- at -- datatailors.com
Nov 9 '06 #14
On 2006-11-08, Gabriel Genellina <ga******@yahoo.com.arwrote:
At Wednesday 8/11/2006 16:51, Peter van Kampen wrote:
>>"""
A = B = [] # both names will point to the same list
"""

I've been bitten by this once or twice in the past, but I have always
wondered what it was useful for? Can anybody enlighten me?

As an optimization, inside a method, you can bind an instance
attribute and a local name to the same object:

def some_action(self):
self.items = items = []
// following many references to self.items,
// but using items instead.

Names in the local namespace are resolved at compile time, so using
items is a lot faster than looking for "items" inside self's
namespace each time it's used.
Nice example.

Thanks,

PterK

--
Peter van Kampen
pterk -- at -- datatailors.com
Nov 9 '06 #15

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

Similar topics

6
by: Kyle E | last post by:
I wrote a program that asks a user questions and records the answers and prints them out at the end. Pretty simple... but I have a few things that I don't like about it....
9
by: Marek Mänd | last post by:
<style type="text/css"> q:after{content:',"'} </style> <q>This will be the shame of CSS</q> claimed Marek Mänd and added that <q>consumers expect to create generated content via CSS where there...
3
by: Grey Plastic | last post by:
How do I pass text that contains a comma into a macro? For example, I have #define ATTRIBUTE(name,type) ... and I want to do ATTRIBUTE(transitions, map<int,int>); However, the last...
3
by: darren | last post by:
Hello, I am posting a html form to a php processing page, which produces a csv file from the form data. However if the user inputs a comma then it screws up my data. So i'd like to know how...
3
by: Jon Maz | last post by:
Hi, A quick one: If you are forming a dynamic sql statement using parameters from a web form, you would normally double up any single inverted commas inputted by the user to stop sql...
9
by: conspireagainst | last post by:
I'm having quite a time with this particular problem: I have users that enter tag words as form input, let's say for a photo or a topic of discussion. They are allowed to delimit tags with spaces...
3
by: bowtie | last post by:
if a code is written like below what does it mean: project1.openform form1 ,,,, i'm mainly concerned about the commas wat do they imply and what can be put after these commas
4
by: riccrom123 | last post by:
Hi, I have a csv file where the commas are skipped by the characther \ for example field1,field2,field3\,field3,field4 I would like to extract the fields and obtain field1 field2...
1
by: vdesio | last post by:
I am new to ASP. I am using the free ezscheduler asp program to create a calendar for my website. The idea is for employees to schedule their work shifts online. I have modified some of the...
5
by: Robert Dodier | last post by:
Hello, I'd like to split a string by commas, but only at the "top level" so to speak. An element can be a comma-less substring, or a quoted string, or a substring which looks like a function...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.