'How to find items from a list of strings based on another list of integers where values are used as index numbers

I have a list of strings like this:

lst = ["this", "that", "cat", "dog", "crocodile", "blah"]

And I have another list of integers like:

index_nr = [2,3]

My goal is to take the numbers from index_nr and get the list items from lst with the corresponding index number. If we stick to the example above, the desired output would be

['cat', 'dog']

Given that, 0: "this", 1: "that", 2: "cat", 3: "dog", 4: "crocodile", and 5: "blah".

I know that:

print(lst[2:4])

would throw the desired output, but I'm not sure how to use the values in index_nr to achive the same outcome.



Solution 1:[1]

You can use list comprehension:

lst = ["this", "that", "cat", "dog", "crocodile", "blah"]
index_nr = [2, 3]

out = [lst[index] for index in index_nr]
print(out)

Prints:

['cat', 'dog']

Or standard for-loop:

out = []
for index in index_nr:
    out.append(lst[index])
print(out)

Solution 2:[2]

You could index lst inside index_nr like this: index_nr = [lst[2],lst[3]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrej Kesely
Solution 2 Davi Magalhães