A summary of answers questions

Alex alex at somewhere.round.here
Wed May 26 18:47:06 EDT 1999


> Some other options:
> 
>    new_list = map(lambda x: list[x], indexes)
> 
> Now this I like! clean, simple, and, I imagine, fast.

Yeah.  But you still need a default argument or something to get a
reference to list into the lambda's namespace and make this expression
reliable.  Probably the posts about it haven't percolated through to you
yet.

new_list = map (lambda x, l = list: l [x], indexes)

will do the trick.

> Here's the "obscure one-liner":
> 
>    import operator
>    list = [1,2,3,4,5,6,7,8,9,10,11]
>    indices = [3,5,9]
>    new_list = map (operator.getitem, len (indices) * [list], indices)
> 
> This certainly works, but it builds a list that is
> len(indices)*len(list) long, which could be pretty darn big, so it
> doesn't seem like a very efficient way to go.

It probably isn't as efficient as some of the alternatives, but not for
this reason. The expression (len (indices) * [list]) makes a list with
(len (indices)) entries, each a pointer to list.  It doesn't make any extra
copies of list along the way.  Which just adds to its obscurity, I
guess. :)

E.g.
>>> l = 5 * [[5]]
>>> l
[[5], [5], [5], [5], [5]]
>>> # Change "all" of these values in one fell swoop:
... 
>>> l [0][0] = 6
>>> l
[[6], [6], [6], [6], [6]]

See you.
Alex.




More information about the Python-list mailing list