Find index item in a list based on the length of a variable in the list

Viewed 419

I have two lists:

list_one = ['I', 'walk','on','the','street','','','','']
list_two = ['','','','','','with','my','pajamas','on']

For both lists my objectives are different. For list_one I would like to find the last item for which the length is greater than 0. And for list_two I would like to find the index of the first variable for which the length is greater than 0.

Right now I have created two functions:

def index_last_long(sentence):
  for index, word in enumerate(sentence):
    if len(word) == 0:
      return index-1

def index_first_long(sentence):
  for index, word in enumerate(sentence):
    if len(word) > 0:
      return index

This does work. However, I think there must be other ways that require less code to perform the same tasks.

Who knows of such approaches?

1 Answers

You could do something like this:

last = next((i for i, x in enumerate(reversed(list_one)) if len(x) > 0), None)
first = next((i for i, x in enumerate(list_two) if len(x) > 0), None)

In case such indexes do not exist, None is returned. Fell free to modify that value, for example with -1 or something else.

Related