Home > Software design >  Python return list from nth element from sublist
Python return list from nth element from sublist

Time:01-10

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

CodePudding user response:

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]

CodePudding user response:

This is what I was looking for

lst2=[sublist[1] for sublist in lst[1:3]]

CodePudding user response:

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))]
  • Related