python return specific elements from list

Solutions on MaxInterview for python return specific elements from list by the best coders in the world

showing results for - "python return specific elements from list"
Amanda
30 May 2020
1# Basic syntax:
2# Using list comprehension:
3selected_elements = [your_list[index] for index in indices]
4
5# Example usage:
6# Say you want to return the elements at indices 1, 4, 6
7your_list = [5, 7, 23, 42, 11, 17, 27]
8indices = [1, 4, 6]
9
10# Running:
11[your_list[index] for index in indices] # Would return:
12--> [7, 11, 27]