Update cast_list.md
This commit is contained in:
@ -5,17 +5,15 @@ tags: utility,list,beginner
|
|||||||
|
|
||||||
Casts the provided value as an array if it's not one.
|
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.
|
Use `isinstance()` to check if the given value is enumerable and return it by using `list()` or encapsulated in a list accordingly.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
def cast_list(val):
|
def cast_list(val):
|
||||||
if isinstance(val, (tuple, list, set, dict)): return list(val)
|
return list(val) if isinstance(val, (tuple, list, set, dict)) else [val]
|
||||||
elif val: return [val]
|
|
||||||
else: return []
|
|
||||||
```
|
```
|
||||||
|
|
||||||
```py
|
```py
|
||||||
cast_list('foo'); # ['foo']
|
cast_list('foo') # ['foo']
|
||||||
cast_list([1]); # [1]
|
cast_list([1]) # [1]
|
||||||
cast_list(('foo', 'bar')); # ['foo', 'bar']
|
cast_list(('foo', 'bar')) # ['foo', 'bar']
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user