Initialize 2D List

PythonPythonBeginner
Practice Now

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

Introduction

In Python, a 2D list is a list of lists. It is a useful data structure for representing grids, tables, and matrices. Initializing a 2D list involves creating a list of lists with a given width and height and initializing each element with a default value.


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/BasicConceptsGroup -.-> python/comments("`Comments`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13660{{"`Initialize 2D List`"}} python/for_loops -.-> lab-13660{{"`Initialize 2D List`"}} python/list_comprehensions -.-> lab-13660{{"`Initialize 2D List`"}} python/lists -.-> lab-13660{{"`Initialize 2D List`"}} python/tuples -.-> lab-13660{{"`Initialize 2D List`"}} python/function_definition -.-> lab-13660{{"`Initialize 2D List`"}} python/default_arguments -.-> lab-13660{{"`Initialize 2D List`"}} python/build_in_functions -.-> lab-13660{{"`Initialize 2D List`"}} end

Initialize 2D List

Write a function initialize_2d_list(w, h, val=None) that initializes a 2D list of given width and height and value. The function should return a list of h rows where each row is a list with length w, initialized with val. If val is not provided, the default value should be None.

def initialize_2d_list(w, h, val = None):
  return [[val for x in range(w)] for y in range(h)]
initialize_2d_list(2, 2, 0) ## [[0, 0], [0, 0]]

Summary

In this challenge, you learned how to initialize a 2D list in Python. You used a list comprehension and range() to generate h rows where each is a list with length w, initialized with a default value. You also learned how to set the default value to None if no value is provided.

Other Python Tutorials you may like