I have a list of objects list
and a list of indexes indexes
and I want to create a new_list
containing objects of the original list at indexes defined this list of indexes.
I tried several ways but couldn't do that.
For example if there are only 2 indexes in indexes
list why the following doesn't work?
new_list = [list[indexes[0]] + list[indexes[1]]]
Will be happy to know the general way resolving this issue, for any length of indexes list.
Asked
Active
Viewed 73 times
0

Prophet
- 32,350
- 22
- 54
- 79
-
If you want to process the list elements separately use zip(list1,list2) – bigbounty Mar 04 '18 at 15:42
-
sacul's solution will work, but the problem with what you have is that you are adding objects of you list rather than lists. it's confusing because you are using a variable 'list', which is the name of the python function for creating lists. if your list object was called L, you could do list([L[indexes[0]]]) + list([L[indexes[1]]]) and it would work. But don't do that. sacul's solution is *the* way to do it. – grovkin Mar 04 '18 at 15:44
1 Answers
3
The following works:
my_list=['a','b','c','d']
my_indices=[1, 3]
new_list = [my_list[i] for i in my_indices if i < len(my_list)]
The above list comprehension will get all elements of my_list
at the indices in my_indices
. The if
is there so that you don't get a IndexError: list index out of range
error.
Your problem was that you were using the +
operator, which concatenates your objects:
>>> [my_list[my_indices[0]] + my_list[my_indices[1]]]
['bd']

sacuL
- 49,704
- 8
- 81
- 106