Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python return list from nth element from sublist

is there a way to:
starting with a list
lst=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

i want a new list with every second(nth) element from the sublist
new list: [2,5,8,11]

and or
a new list with every second(nth) element from lst[1:3]
new list: [5,8]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

thanks in advance

>Solution :

If this is a recurring operation, you’ll probably want to turn this into a reusable function. Feel free to remove the type annotations.

def get_nth_elements(list_of_lists: List[List[Any]], n: int) -> List[Any]:
   """Get the nth element from each list in a given list of lists"""
   return [sub_list[n] for sub_list in list_of_lists]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading