A couple of quick questions

Doug Hellmann doughellmann at mindspring.com
Mon May 24 16:20:40 EDT 1999


cbarker at jps.net wrote:
> 
> Hi,
> 
> I've been using Python for a few months now, and I have a couple of
> things I havn't figured out how to do, that would be handy
> 
> 1) loop a known number of times, without creating a list of indexes:
> 
> for i in range(N):
>         # do something
> 
> works just fine, unless N is very large. if it's large, it wastes
> memory, if it's very large it can be impossible!

Check out xrange().  It creates a thing that behaves like a sequence,
but doesn't actually instantiate all of the members of the sequence like
range() does.

> 2) Is there a "case" construct?
> 
> I can use if...elif...elif...elif...else, but it's once, again, not
> very elegant.

If you have one variable which controls a switch, you could create a
dispatch table using a dictionary.

dispatch = {
 'one':func_one,
 'two':func_two,
}

func_to_call = dispatch[ switch_variable ]
func_to_call()

On the other hand, if your code doesn't break down neatly into separate
functions, that isn't always cleaner than a large if/elif/else.

> 3) lists of indexes:
> 
> let's say I have a list of the indexes of another list that I want. Is
> there a way to return the corresponding elements without a loop?
> 
> example:
> 
> list = [1,2,3,4,5,6,7,8,9,10,11]
> indexes = [3,5,9]
> new_list = []
> for i in indexes:
>         new_list.append(list[i])
> 
> This just isn't elegant (or fast!). What I want to be able to do is
> something like:
> 
> new_list = list[indexes]
> 
> Is there a way to do this?

Why not store references to the objects in the second list, instead of
the indexes?  Let the reference counter do its job.

Doug




More information about the Python-list mailing list