Python return list from nth element from sublist

Question:

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]

thanks in advance

Asked By: Pan

||

Answers:

To create a new list with every second element from the entire list , you can do the following:

new_list = [lst[i][1] for i in range(len(lst))]
Answered By: Gurnoor Singh

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]
Answered By: MangoTree_Dev

This is what I was looking for

lst2=[sublist[1] for sublist in lst[1:3]]
Answered By: Pan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.