Files
30-seconds-of-code/snippets/cast_list.md
Isabelle Viktoria Maciohsek d30ac2818b Update tags for cast_list
2020-04-07 19:54:40 +03:00

20 lines
439 B
Markdown

---
title: cast_list
tags: 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.
```py
def cast_list(val):
return list(val) if isinstance(val, (tuple, list, set, dict)) else [val]
```
```py
cast_list('foo') # ['foo']
cast_list([1]) # [1]
cast_list(('foo', 'bar')) # ['foo', 'bar']
```