Python is a predominant language in the programming world today, majorly due to its simplicity and versatility.
One of the data types that Python supports is lists, which can be visualized as a collection of elements.
Lists can exist in multiple dimensions, one of which is a two-dimensional (2D) list, otherwise known as the matrix. Now in this tutorial, we are going to explore how you can insert an element into a 2D list.
Step 1: Understanding 2D List
A 2D list in Python is a list that contains other lists. These inner lists function as the rows and the elements inside each row are the columns. In the world of programming, this structure resembles something like a table. For example, a 2D list can be imagined like this:
2D List: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Which looks like: 1 2 3 4 5 6 7 8 9
Step 2: Initialization of 2D List
We initialize a 2D list the same way we initialize a normal list, with the only difference being what is contained within the list. Below is an example of initializing a 2D list in Python:
1 2 |
# Declaring 2D list matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
Step 3: Inserting an element
Inserting a new element into a 2D list in Python can be done using the append() or insert() function. Let’s explore this using an example:
1 2 3 |
# Let's insert 10 at the end of the first list matrix[0].append(10) print(matrix) |
The full code:
1 2 3 4 5 6 |
# Declaring 2D list matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Let's insert 10 at the end of the first list matrix[0].append(10) print(matrix) |
The output:
[[1, 2, 3, 10], [4, 5, 6], [7, 8, 9]]
Conclusion
In this tutorial we have covered the concept of a two-dimensional list in Python, how to initialize it, and finally how to insert an element into it. This is a crucial concept that is often used while working with NumPy arrays, databases, and data manipulation in Python.