Files
30-seconds-of-code/snippets/cast-list.md
Angelos Chalaris f6a215e9e3 Kebab file names
2023-04-27 22:00:06 +03:00

531 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
Cast to list list colorful-pots 2019-08-20T12:47:43+03:00 2020-11-02T19:27:07+02:00

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']