Adding same text to two different lists
How can I add the same text(s) to two开发者_运维技巧 or more different lists?
For example, this is what I am doing:
>>> msg = 'Do it'
>>> first = list()
>>> second = list()
>>> first.append(msg)
>>> second.append(msg)
Not only this is causing redundancy, I think it makes for poor code. Is there any way I can add the same text to two or more different lists in one go?
first, second = [], []
for lst in (first, second):
lst.append(msg)
But it would be better if you'd tell us what problem are you solving.
This is inefficient. Why not make one list and then copy()
it when you need to differentiate the two?
msg = 'Do it'
theList = [ ]
theList.append( msg )
# Later...
first = theList
second = theList.copy( )
EDIT
I saw your edit. Why not do:
header = [ ]
# Generate header here.
# Later...
for theFile in theFiles:
theFile.write( header )
Why do you need keeping 2 identical lists, instead of one? Describe your task in more details.
Without the write trick If you have to set the first element after the construction of the list because you don't know it before the simplest is to reserve the place
first, second = [], []
for lst in (first, second):
lst.append(None)
... work on your lists
msg = 'Do it'
for lst in (first, second):
lst[0] = msg
精彩评论