1️⃣

10.1 Introduction

Introduction to 2D Lists

So far, we've only covered one-dimensional (1D) lists, where each element in the list is its own element. However, we can have multi-dimensional lists, such as a 2D list, where each element in the list is another list.

This can be presented in a table where the indices of the outer list are rows and the indices of the inner lists are columns. For example, the following table could represent the following 2D list in Python:

Table:

0

1

2

3

0

'hello'

'docs'

'google'

'this'

1

'world'

'slides'

'amazon'

'is'

2

'code'

'sheets'

'facebook'

'python'

Python list:

my_list = [
	['hello', 'world', 'code'],
	['docs', 'slides', 'sheets'],
	['google', 'amazon', 'facebook'],
	['this', 'is', 'python']
]

View code on GitHub.

💡

While you could technically write the sublists in one line, it's generally better style and organization if you write multi-dimensional lists on separate lines like this.

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.