Picking out items from a python list which have specific indexes

221

Solution 1

[main_list[x] for x in indexes]

This will return a list of the objects, using a list comprehension.

Solution 2

t = []
for i in indexes:
    t.append(main_list[i])
return t

Solution 3

map(lambda x:main_list[x],indexes)

Solution 4

If you're good with numpy:

import numpy as np
main_array = np.array(main_list) # converting to numpy array
out_array = main_array.take([2, 4, 5])
out_list = out_array.tolist() # if you want a list specifically

Solution 5

I think Yuval A's solution is a pretty clear and simple. But if you actually want a one line list comprehension:

[e for i, e in enumerate(main_list) if i in indexes]
Share:
221

Related videos on Youtube

Pennvad
Author by

Pennvad

Updated on April 18, 2022

Comments

  • Pennvad
    Pennvad about 2 years

    Good morning,

    We are using the scope:

    https://www.googleapis.com/auth/calendar.app.created

    Make secondary Google calendars, and see, create, change, and delete events on them

    We are getting PERMISSION_DENIED when we try to create a calendar

    Is anyone familiar with any issue in calendar.app.created? Does calendar.app.created usually work?

    Please note that we cannot use the scope https://www.googleapis.com/auth/calendar because it is a Restricted Scope, and we need to use the non-sensitive scope calendar.app.created.

    Thank you.

  • Matthew Schinckel
    Matthew Schinckel about 15 years
    List comprehensions are very cool, and easy to read. They often turn out to be faster than iterating, too.
  • Admin
    Admin about 15 years
    While this is less elegant than a list comprehension, I like it better as an answer for someone completely new to Python.
  • Ben
    Ben about 15 years
    Ah! That's the kind of thing I was thinking of. Very neat!
  • Ben
    Ben about 15 years
    This is really nice. Exactly the kind of thing I wanted, without realising it!
  • Nathan Chappell
    Nathan Chappell over 3 years
    very pythonic
  • buhtz
    buhtz about 2 years
    This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
  • Xuemin Chi
    Xuemin Chi about 2 years
    Okay, Thank you very much! I will be more careful in commenting!
  • Pennvad
    Pennvad almost 2 years
    Thank you Kessy however we cannot use auth/calendar which is a restricted scope, we are looking to instead use /auth/calendar.app which is a non-sensitive scope.
  • Kessy
    Kessy almost 2 years
    I understand that but the calendar.app is deprecated. You can see the available scopes for calendar on OAuth 2.0 Scopes for Google APIs. You can also check this other question where it is stated that it is not a valid scope: stackoverflow.com/questions/64474688/…