Files
30-seconds-of-code/snippets/cast_list.md
Angelos Chalaris fe368c3673 Update cast_list.md
2019-10-09 13:14:32 +03:00

20 lines
449 B
Markdown

---
title: cast_list
tags: utility,list,beginner
---
Casts the provided value as an array 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']
```