473,241 Members | 1,694 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,241 software developers and data experts.

list/tuple/dict question

hi guys/gals...

got a basic question that i can't get my hands around.

i'm trying to programatically create/use a list/tuple (or whatever the right
phrase in pyton is!!)

basically, something like:
foo = []
foo.append('cat')
foo.append('dog')

foo[1] = [] (and in this case, i really want to have a list called 'cat' to
be created!!)

when i've tried this, i don't get a list called 'cat', instead (as i
expected) the foo[1] is now a [] (list))

so foo is now
['cat', [] ]

ultimatelly , i want to be able to dynamically create a number of lists that
i name/create/manipulate on the fly, within the test app.

ie, be able to then create a list/array cat = ['a','b','c',....]

a dict doesn't seem to work, as it is essentially a series of key/values,
which isn't exactly what i want...

thoughts/comments/code samples would be reatly appreciated.

looking at various sites/samples cia google hasn't helped...

thanks
Aug 17 '08 #1
3 1721
bruce a écrit :
hi guys/gals...

got a basic question that i can't get my hands around.

i'm trying to programatically create/use a list/tuple (or whatever the right
phrase in pyton is!!)

basically, something like:
foo = []
foo.append('cat')
foo.append('dog')

foo[1] = [] (and in this case, i really want to have a list called 'cat' to
be created!!)
This doesn't "create a list called 'cat', it replaces the second element
(remember, sequences are zero-based) of list 'foo' with an empty list.
when i've tried this, i don't get a list called 'cat', instead (as i
expected) the foo[1] is now a [] (list))

so foo is now
['cat', [] ]
Indeed.
ultimatelly , i want to be able to dynamically create a number of lists that
i name/create/manipulate on the fly, within the test app.

ie, be able to then create a list/array cat = ['a','b','c',....]

a dict doesn't seem to work, as it is essentially a series of key/values,
which isn't exactly what i want...
Why do you think it's not what you want ?

lists = dict()
lists['cat'] = []
lists['cat'].extend(['a', 'b', 'c', 'd'])
thoughts/comments/code samples would be reatly appreciated.
Please provide more informations about your use case.
Aug 18 '08 #2
Hi Bruce,

I think I get what you're asking for -- you want to actually end up
with a local variable 'cat' which points to an empty list, so that you
can then do

cat.append('foot')

or whatever.

The problem with the last line of this code (based on your attempt):

foo=[]
foo.append('cat')
foo[0] = []

is that Python doesn't evaluate the left hand side of an assignment to
figure out what variable name you want. foo[0] doesn't get replaced
with 'cat' as the variable name. Instead, Python sees this line of
code as a request to store an empty list as the 0th item in the foo
array.

In C or C++, what you want to do is impossible. However, in Python,
there's a way to specify the name of a local variable at runtime:

locals()['cat'] = []

locals() is a function call that returns a dictionary mapping all
local variable names to their values. Just like "foo[0] = []" above
will store an empty list into the 0th item in foo, "locals()['cat'] =
[]" will store an empty list in the 'cat' entry in the locals
dictionary.

Once you've done that, you can then refer to the variable cat as
usual:

cat.append('foot')

etc.

Note that you can also *read* the value of a local variable using the
locals dictionary:

locals()['cat']

will return a list. Trying to access an entry in the locals
dictionary that isn't defined will raise an exception, much like if
your code tried to access a variable that didn't exist.

And finally, you can also create a global variable -- one that, even
though it's defined from within a function, will be accessible
anywhere in the module -- by using the globals() dictionary instead.

Hope this helps, and good luck --
Michael
On Aug 18, 3:32*am, Bruno Desthuilliers <bruno.
42.desthuilli...@websiteburo.invalidwrote:
bruce a écrit :
hi guys/gals...
got a basic question that i can't get my hands around.
i'm trying to programatically create/use a list/tuple (or whatever the right
phrase in pyton is!!)
basically, something like:
*foo = []
*foo.append('cat')
*foo.append('dog')
*foo[1] = [] (and in this case, i really want to have a list called'cat' to
be created!!)

This doesn't "create a list called 'cat', it replaces the second element
* (remember, sequences are zero-based) of list 'foo' with an empty list..
when i've tried this, i don't get a list called 'cat', instead (as i
expected) the foo[1] is now a [] (list))
so foo is now
*['cat', [] ]

Indeed.
ultimatelly , i want to be able to dynamically create a number of liststhat
i name/create/manipulate on the fly, within the test app.
ie, be able to then create a list/array cat = ['a','b','c',....]
a dict doesn't seem to work, as it is essentially a series of key/values,
which isn't exactly what i want...

Why do you think it's not what you want ?

lists = dict()
lists['cat'] = []
lists['cat'].extend(['a', 'b', 'c', 'd'])
thoughts/comments/code samples would be reatly appreciated.

Please provide more informations about your use case.
Aug 18 '08 #3
En Mon, 18 Aug 2008 11:02:20 -0300, gundlach <gu******@gmail.comescribió:
In C or C++, what you want to do is impossible. However, in Python,
there's a way to specify the name of a local variable at runtime:

locals()['cat'] = []

locals() is a function call that returns a dictionary mapping all
local variable names to their values. Just like "foo[0] = []" above
will store an empty list into the 0th item in foo, "locals()['cat'] =
[]" will store an empty list in the 'cat' entry in the locals
dictionary.
>From http://docs.python.org/lib/built-in-funcs.html#l2h-47
locals(): Update and return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter.

So modifying locals() is unsafe at least. Do as everyone else suggested and use a dictionary. If using ns['cat'] really annoys you so much, define a generic attribute container:

class NS(object): pass

ns = NS()
ns.cat = 1
ns.dog = 2
ns.zoo = ns.cat + ns.dog

--
Gabriel Genellina

Aug 19 '08 #4

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

Similar topics

17
by: Pierre Fortin | last post by:
Hi, Is the following a reasonable generic approach for converting python returned tuples/lists into dicts...? I'm not advocating library functions also return dicts (I'd probably spend more...
16
by: flyaflya | last post by:
a = "(1,2,3)" I want convert a to tuple:(1,2,3),but tuple(a) return ('(', '1', ',', '2', ',', '3', ')') not (1,2,3)
25
by: beginner | last post by:
Hi, I am wondering how do I 'flatten' a list or a tuple? For example, I'd like to transform or ] to . Another question is how do I pass a tuple or list of all the aurgements of a function to...
0
by: bruce | last post by:
Hi Fredrik... so, this still doesn't get me an array called 'cat', or 'dog' or do i somehow use stuff to add/extract the vals...??? thanks -----Original Message-----
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.