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.
CodePudding user response:
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)
CodePudding user response:
You could index lst
inside index_nr
like this: index_nr = [lst[2],lst[3]]