Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 670
Ben Avatar asked Apr 07 '09 09:04

Ben


People also ask

How do you get a specific index from a list?

To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument. The index() method returns an integer that represents the index of first match of specified element in the List.

How do you select a specific item in a list Python?

To select elements from a Python list, we will use list. append(). We will create a list of indices to be accessed and the loop is used to iterate through this index list to access the specified element. And then we add these elements to the new list using an index.

How do you get the index of an element in a list of lists in Python?

In Python to find a position of an element in a list using the index() method and it will search an element in the given list and return its index.


Video Answer


1 Answers

[main_list[x] for x in indexes] 

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

like image 119
Matthew Schinckel Avatar answered Sep 20 '22 22:09

Matthew Schinckel