tags:

views:

68

answers:

4

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?

+4  A: 
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.

SilentGhost
I have some blocks of text that need to be appended to two different lists. I think your approach should work. Wonder why I didn't think of it :)
sukhbir
@Pulp: why do you have those lists? that's the real question.
SilentGhost
I will be writing these two lists to two separate files. However, the header of both the lists is the same. Hence the common text. (By header I mean, the first two elements of the list are the same)
sukhbir
@Pulp: I'd rather have a header separate from the rest of the file content then.
SilentGhost
@SilentGhost: Well the biggest problem is that I already have appended the data to the list before hand, and I if I prepend it, won't it slow down things since the entire list will be shifted?
sukhbir
And to be honest, if I change the way stuff is added to a list, I will go mad :) Thanks for the above though, it serves my purpose well enough for now.
sukhbir
@PulpFiction The point if it slow down things depends only on the size of the list, not the size of list content because list contains only pointers to elements.
Xavier Combelle
A: 

Why do you need keeping 2 identical lists, instead of one? Describe your task in more details.

Shaman
Only some text is identical, I will add some text later that will differentiate the lists.
sukhbir
+2  A: 

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 )
katrielalex
Aah! This will also work.
sukhbir
A: 

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
Xavier Combelle