Cast to list

Python, List · Nov 2, 2020

Casts the provided value as a list if it's not one.

  • Use isinstance() to check if the given value is enumerable.
  • Return it by using list() or encapsulated in a list accordingly.
def cast_list(val):
  return list(val) if isinstance(val, (tuple, list, set, dict)) else [val]
cast_list('foo') # ['foo']
cast_list([1]) # [1]
cast_list(('foo', 'bar')) # ['foo', 'bar']

More like this

  • Map list to dictionary

    Maps the values of a list to a dictionary using a function.

    Python, List · Nov 2, 2020

  • Find matching value

    Finds the value of the first element in the given list that satisfies the provided testing function.

    Python, List · Nov 2, 2020

  • Find last matching value

    Finds the value of the last element in the given list that satisfies the provided testing function.

    Python, List · Nov 2, 2020