retrieving from list

Courageous jkraska1 at san.rr.com
Mon May 29 16:48:49 EDT 2000


> def func(arg):
>     a = []
>     a.append('foo')
>     b = []
>     b.append('bar')
>     a.append(b)
>     # now I have a = ['foo', ['bar']]
>     return a[arg][arg]
> 
> The last line is where the problem lies. How can 'arg' be able to refer to
> 'foo' or 'bar'? Should 'arg' be a string of comma seperated values which
> would be parsed within the function in order to refer to the proper member
> of the list? For example, '0' for 'foo' and '0,0' for 'bar'?
> 
> Any ideas to solve this little problem would be much appreciated,

You need to read about tuples, I think:

def makelist():
    a=[]
    a.append('foo')
    b=[]
    b.append('bar')
    a.append(b)
    return a

def get(mylist,tup):
    item=mylist
    for i in tup: item=item[i]
    return item

def test():
    mylist = makelist()
    item = get ( mylist, (0,) )
    print item
    item = get ( mylist, (1,0) )
    print item


>>> import f
>>> f.test()
foo
bar
>>>



More information about the Python-list mailing list