Cast to List

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, sometimes we need to convert a value into a list. However, if the value is already a list, we don't want to create a nested list. In this challenge, you will create a function that takes a value and returns it as a list, unless it is already a list or another iterable.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13597{{"`Cast to List`"}} python/variables_data_types -.-> lab-13597{{"`Cast to List`"}} python/conditional_statements -.-> lab-13597{{"`Cast to List`"}} python/lists -.-> lab-13597{{"`Cast to List`"}} python/tuples -.-> lab-13597{{"`Cast to List`"}} python/function_definition -.-> lab-13597{{"`Cast to List`"}} python/data_collections -.-> lab-13597{{"`Cast to List`"}} python/build_in_functions -.-> lab-13597{{"`Cast to List`"}} end

Cast to List

Write a function cast_list(val) that takes a value as an argument and returns it as a list. If the value is already a list, return it as is. If the value is not a list but is iterable, return it as a list. If the value is not iterable, return it as a single-item list.

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

Summary

In this challenge, you learned how to create a function that casts a value to a list if it is not already a list or another iterable. You used isinstance() to check if the value is iterable and returned it using list() or encapsulated it in a list accordingly.

Other Python Tutorials you may like