Home > database >  List of the first item in a sublist
List of the first item in a sublist

Time:11-28

I want a list that displays the first element of the sublists I input.

def irstelementsf(w):
    return [item[0] for item in w]

Which works, but when I try doing

fisrtelements([[10,10],[3,5],[]])

there's an error because of the [], how can I fix this?

CodePudding user response:

Add a condition to your list comprehension so that empty lists are skipped.

def firstelements(w):
    return [item[0] for item in w if item != []]

If you wish to represent that empty list with something but don't want an error you might use a conditional expression in your list comprehension.

def firstelements(w):
    return [item[0] if item != [] else None for item in w]
>>> firstelements([[10,10],[3,5],[]])
[10, 3, None]

CodePudding user response:

Add a condition to check if the item has data.

def firstelements(w):
    return [item[0] for item in w if item]

Below are 3 more ways you can write it that don't require a condition. filter strips out None/"Empty" values.

def firstelements(w):
    return list(zip(*filter(None, w)))[0]
def firstelements(w):
    return [item[0] for item in filter(None, w)]
def firstelements(w):
    return [i for (i,*_) in filter(None, w)]
  • Related