Wednesday, April 20, 2011

Picking out items from a python list which have specific indexes

I'm sure there's a nice way to do this in Python, but I'm pretty new to the language, so forgive me if this is an easy one!

I have a list, and I'd like to pick out certain values from that list. The values I want to pick out are the ones whose indexes in the list are specified in another list.

For example:

indexes = [2, 4, 5]
main_list = [0, 1, 9, 3, 2, 6, 1, 9, 8]

the output would be:

[9, 2, 6]

(i.e., the elements with indexes 2, 4 and 5 from main_list).

I have a feeling this should be doable using something like list comprehensions, but I can't figure it out (in particular, I can't figure out how to access the index of an item when using a list comprehension).

Thanks,

Ben

From stackoverflow
  • t = []
    for i in indexes:
        t.append(main_list[i])
    return t
    
    Lars Wirzenius : While this is less elegant than a list comprehension, I like it better as an answer for someone completely new to Python.
  • I think Yuval A's solution is a pretty clear and simple. But if you actually want a one line list comprehension:

    [e for i, e in enumerate(main_list) if i in indexes]
    
    Yuval A : Actually this is much more elegant :) Although slightly less readable
    Ben : Ah! That's the kind of thing I was thinking of. Very neat!
  • [main_list[x] for x in indexes]
    

    This will return a list of the objects, using a list comprehension.

    Yuval A : now THIS is elegant. +1
    Matthew Schinckel : List comprehensions are very cool, and easy to read. They often turn out to be faster than iterating, too.
    Ben : This is really nice. Exactly the kind of thing I wanted, without realising it!
  • map(lambda x:main_list[x],indexes)

0 comments:

Post a Comment