1

I have a list that looks like the following one:

my_list = [[[(2,3,4,5)]],[[8,2,4,2]],[[9,0,0,0]]]

Now, I want to find a way to make a new list zero_list whose elements will be the 0th entries of each element in my_list. That is

zero_list = [2, 8, 9]

How could I make a for loop for iterating the 0th element of a list whose elements are lists themselves? Of course in my real example I have a much bigger such list with thousands of entries who are lists themselves.

P.S. I understand this is probably an easy question but I could not figure it out.

4
  • Do sublists have random level of depth?
    – Chris
    Commented Jan 28, 2021 at 5:37
  • All of them are the same. A solution to the example above would help me for a solution to the much larger problem I currently have. There is only 1 level of depth. main list whose entries are lists of real numbers.
    – Marion
    Commented Jan 28, 2021 at 5:42
  • The sample my_list has three lists which have 3, 2, 2 depths respectively. Can you change your sample to reflect your situation?
    – Chris
    Commented Jan 28, 2021 at 5:45
  • is tuple also part of your code ? Commented Jan 28, 2021 at 5:46

2 Answers 2

2

For any depth list you can use this recursive function

def get_first(seq):
    if isinstance(seq, (tuple, list)):
        return get_first(seq[0])
    return seq

def get_zero_list(seq):
    return [get_first(i) for i in seq]



my_list = [[[[[[[[(2,3,4,5)]]]]]]],[[8,2,4,2]],[[9,0,0,0]]]

print(get_zero_list(my_list)) # [2, 8, 9]

my_list = [[[[[[[[(2,3,4,5)]]]]]]],[[[[[[[('first', 3)]]]], 2, 3],2,4,2]],[[([['a', 2]]),0,0,0]]]

print(get_zero_list(my_list)) # [2, 'first', 'a']
6
  • Thanks but this is not what I need. I need a list whose output is the first element of each sublist.
    – Marion
    Commented Jan 28, 2021 at 5:47
  • 1
    That is a very good answer. I am wondering though if there is a standard method to do this instead of defining these two functions.
    – Marion
    Commented Jan 28, 2021 at 6:37
  • thanks, it was an interesting question as well, afaik none exists, but if I do find one, I will edit it in Commented Jan 28, 2021 at 6:38
  • Why I struggle to generalize to the second index? def get_second(seq): if isinstance(seq, (tuple, list)): return get_second(seq[1]) return seq def get_first_list(seq): return [get_second(i) for i in seq]
    – Marion
    Commented Jan 28, 2021 at 6:52
  • what should you do if there is no element in second or the nth index? what is the behavior you expect? the new list should only include the nth element only if it exists in a nested list? Commented Jan 28, 2021 at 6:59
1
Zero_list = [ items[0] for sublist in my_list for items in sublist] 

Not the answer you're looking for? Browse other questions tagged or ask your own question.