Files
30-seconds-of-code/snippets/cast_list.md
2020-09-15 16:25:15 +03:00

441 B

title, tags
title tags
cast_list list,beginner

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

  • Use isinstance() to check if the given value is enumerable and 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']