creating lists question?

Steve dippyd at yahoo.com.au
Tue Mar 23 21:39:32 EST 2004


Matt Gerrans wrote:

> This would do the trick:
> 
> for item in list1:
>  exec( item + ' = []' )
> 
> Of course, there are the usual cautions about using exec() and error
> handling...

With respect Matt, Spisatus has already suggested he is 
a newbie, and therefore probably hasn't got a clue what 
those cautions are.

For the benefit of Spisatus, what happens if one of 
those prospective list names is something like this?

"f=open('SOME_IMPORTANT_FILE','w'); f.close(); aaa"

Don't try this at home if you actually have an 
important file called SOME_IMPORTANT_FILE.

If the names of the lists can be created by the user 
who runs the program, then this is a terrible security 
hole, just waiting for a malicious (or unlucky) user to 
exploit.

Seems to me, rather than hand Spisatus a possible 
security vulnerability, we should ask him why he wants 
to create a variable number of seperate lists. I'm 
guessing there is probably a simpler way of getting the 
result he wants.

Originally, Spisatus asked:

 > I'm trying to create a series of list from a loop is 
 > this possible? Let me give you an example:
 >
 > list1 = ["aaa", "bbb", "ccc", "ddd", "eee"]
 >
 > for element in list1:
 >   a = element
 >   a = []
 >
 > I want a new list created for every element in 
list1, > how can I do this.

Yes, it is possible, but why do you think you need to 
do this?

I can think of a couple of alternative methods of doing 
something like this. Suppose you want to initialise a 
number of lists:

aaa = []; bbb = []; ccc = []

etc. Tedious and boring, but it is safe and easy to 
maintain and easy to understand. The disadvantage is 
that you need to know how many lists you want beforehand.

Is there any reason why the individual lists have to be 
seperate variables? If not, then you can do something 
like this:

myListVariables = ["aaa", "bbb", "ccc"]
myLists = {}
for element in myListVariables:
     myLists[element] = []

and then access each list with myLists["aaa"] etc. This 
is quite safe. Even if the user tries to create a list 
with a "dangerous" name, it won't do anything. It is 
just a string of letters and numbers.

I must admit I am stumped about one thing though. I 
originally came up with this (non-)solution to the case 
where you do know how many lists you need:

aaa, bbb, ccc = ([],) * 3

Unfortunately, this doesn't do what I expected it to 
do. I thought that the above line would be equivalent to:

aaa, bbb, ccc = ([], [], [])

but in fact they are three names for the same list, 
equivalent to aaa = bbb = ccc = []

Why is this? Bug or feature?


-- 
Steven D'Aprano





More information about the Python-list mailing list