Files
30-seconds-of-code/snippets/cast_list.md
2019-10-09 17:14:06 +08:00

473 B

title, tags
title tags
cast_list utility,list,beginner

Casts the provided value as an array if it's not one.

Use isinstance() to check if the given value is a list and return it as-is or encapsulated in a list accordingly.

def cast_list(val):
  if isinstance(data, (tuple, list, set, dict)): return list(data)
  elif data: return [data]
  else: return []
cast_list('foo'); # ['foo']
cast_list([1]); # [1]
cast_list(('foo', 'bar')); # ['foo', 'bar']