tolist#
- tolist(obj=None, objtype=None, keepnone=False, coerce='default')[source]#
Make sure object is always a list (note:
sc.tolist()
/sc.promotetolist()
are identical).Used so functions can handle inputs like
'a'
or['a', 'b']
. In other words, if an argument can either be a single thing (e.g., a single dict key) or a list (e.g., a list of dict keys), this function can be used to do the conversion, so it’s always safe to iterate over the output.While this usually wraps objects in a list rather than converts them to a list, the “coerce” argument can be used to change this behavior. Options are:
‘none’ or None: do not coerce
‘default’: coerce objects that were lists in Python 2 (range, map, dict_keys, dict_values, dict_items)
‘tuple’: all the types in default, plus tuples
‘full’: all the types in default, plus tuples and arrays
- Parameters:
obj (anything) – object to ensure is a list
objtype (anything) – optional type to check for each element; see
sc.checktype()
for detailskeepnone (bool) – if
keepnone
is false, thenNone
is converted to[]
; else, it’s converted to[None]
coerce (str/tuple) – tuple of additional types to coerce to a list (as opposed to wrapping in a list)
See also
sc.mergelists()
to handle multiple input arguments.Examples:
sc.tolist(5) # Returns [5] sc.tolist(np.array([3,5])) # Returns [np.array([3,5])] -- not [3,5]! sc.tolist(np.array([3,5]), coerce=np.ndarray) # Returns [3,5], since arrays are coerced to lists sc.tolist(None) # Returns [] sc.tolist(range(3)) # Returns [0,1,2] since range is coerced by default sc.tolist(['a', 'b', 'c'], objtype='number') # Raises exception def myfunc(data, keys): keys = sc.tolist(keys) for key in keys: print(data[key]) data = {'a':[1,2,3], 'b':[4,5,6]} myfunc(data, keys=['a', 'b']) # Works myfunc(data, keys='a') # Still works, equivalent to needing to supply keys=['a'] without tolist()
New in version 1.1.0: “coerce” argumentNew in version 1.2.2: default coerce valuesNew in version 2.0.2: tuple coersion