Skip to content

List helpers

We found ourselves at EcoAct reusing again and again the following helpers. They are heavily inspired from C# LINQ spirit.

first_or_default

Take the first element of a list that satisfies a specific condition.

Returns None if no element matches the specified condition.

The Unit test should be self explanatory

 data = [1, 2, 3, 1, 2, 3]
self.assertEqual(first_or_default(data, lambda x: x > 2), 3)
self.assertEqual(first_or_default(data), 1)
self.assertEqual(first_or_default(None), None)

first_transformed_or_default

Take the first element of a list that satisfies a specific condition and apply a transformation to this element.

Returns None if no element matches the specified condition.

The Unit test should be self explanatory

data = [1, 2, 3, 1, 1, 2, 3]
self.assertEqual(first_transformed_or_default(data, lambda x: x * 3 if x > 2 else None), 9)

group_by_value

Sometimes a code snippet is worth a thousands words

data = [1, 2, 3, 1, 1, 2, 3]
self.assertEqual(group_by_value(data), {1: [0, 3, 4], 2: [1, 5], 3: [2, 6]})

group_by_value thus eats a sequence and spits a dict where

  • keys are all unique sequence element values
  • values are indexes where the corresponding key sits in the sequence

lselect

The builtin python filter method returns an Iterator and not a list.

This is convenient if you plan to directly foreach on the filter result only once, but not so convenient if you need to do so several times, or access a particular element. For that we use lselect.

data = [1, 2, 3, 1, 1, 2, 3]
self.assertEqual(lselect(data, lambda x: x > 2), [3, 3])
self.assertEqual(lselectfirst(data, lambda x: x > 2), 3)

lselectfirst (deprecated)

Should be deprecated, use first_or_default in its stead