Search code examples
pythonlistprintingindices

Python - how to print values of a list given many indexes?


I have for example the index values:

x = [1, 4, 5, 7]

and I have a list of elements:

y = ['this','is','a','very','short','sentence','for','testing']

I want to return the values

['is','short','sentence','testing']

When I attempt to print say:

y[1]

it will gladly return ['is']. However, when I do print(y[x])) it will simply return nothing. How can I print all those indexes? Bonus: Then join them together.


Solution

  • This should do the job:

    ' '.join([y[i] for i in x])