Efficiently shorten a list till first and last appearance of a value different from None

Viewed 31

I have lists of the style:

[None, ..., None, "c", 1, 3, None, None, 4.3, "b", None, "4", None, ..., None]

that I would like to efficiently shorten to:

["c", 1, 3, None, None, 4.3, "b", None, "4"]

Straight forward I could do:

def _shorten(long_list):
  start = False
  short_list = []
  for e in long_list:
    if e:
      start = True
    if start:
      short_list.append(e)
  return short_list

reversed(_shorten(reversed(_shorten(long_list))))
1 Answers

Try:

lst = [None, None, None, None]

i = 0
while i < len(lst) - 1 and lst[i] is None:
    i += 1

j = len(lst) - 1
while j > 0 and lst[j] is None:
    j -= 1

print(lst[i : j + 1])

EDIT: Removed the first O(n^2) answer

Related