The Wayback Machine - https://web.archive.org/web/20241120201148/https://www.geeksforgeeks.org/python-using-2d-arrays-lists-the-right-way/
Open In App

Python | Using 2D arrays/lists the right way

Last Updated : 20 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python provides powerful data structures called lists, which can store and manipulate collections of elements. Also provides many ways to create 2-dimensional lists/arrays. However one must know the differences between these ways because they can create complications in code that can be very difficult to trace out. In this article, we will explore the right way to use 2D arrays/lists in Python.

Using 2D arrays/lists the right way

Using 2D arrays/lists the right way involves understanding the structure, accessing elements, and efficiently manipulating data in a two-dimensional grid. When working with structured data or grids, 2D arrays or lists can be useful. A 2D array is essentially a list of lists, which represents a table-like structure with rows and columns.

Creating a 1-D list

In Python, Initializing a collection of elements in a linear sequence requires creating a 1D array, which is a fundamental process. Although Python does not have a built-in data structure called a ‘1D array’, we can use a list that can achieve the same functionality. Python lists are dynamic and versatile, making them an excellent choice for representing 1D arrays. Let’s start by looking at common ways of creating a 1d array of size N initialized with 0s.

Creating 1D List using Naive Methods

Manually initializing and populating a list without using any advanced features or constructs in Python is known as creating a 1D list using “Naive Methods”.

Python
N = 5
ar = [0]*N
print(ar)

Output

[0, 0, 0, 0, 0]

Creating 1D List using List Comprehension

Here we are multiplying the number of rows by the empty list and hence the entire list is created with every element zero.

Python
N = 5
arr = [0 for i in range(N)]
print(arr)

Output

[0, 0, 0, 0, 0]

Creating a 2-D list

Using 2D arrays/lists the right way involves understanding the structure, accessing elements, and efficiently manipulating data in a two-dimensional grid. By mastering the use of 2D arrays, you can significantly improve your ability to handle complex data and efficiently perform various operations.

Creating 2D List using Naive Method

Here we are multiplying the number of columns and hence we are getting the 1-D list of size equal to the number of columns and then multiplying it with the number of rows which results in the creation of a 2-D list.

Python
rows, cols = (5, 5)
arr = [[0]*cols]*rows
print(arr)

Output

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

Note: Using this method can sometimes cause unexpected behaviors. In this method, each row will be referencing the same column. This means, even if we update only one element of the array, it will update the same column in our array.

Python
rows, cols = (5, 5)
arr = [[0]*cols]*rows
print(arr, "before")

arr[0][0] = 1 # update only one element
print(arr, "after")

Output

([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], 'before')
([[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]], 'after')

Creating 1D List using List Comprehension

Here we are basically using the concept of list comprehension and applying a loop for a list inside a list and hence creating a 2-D list.

Python
rows, cols = (5, 5)
arr = [[0 for i in range(cols)] for j in range(rows)]
print(arr)

Output

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

Creating 1D List using Empty List

Here we are appending zeros as elements for a number of columns times and then appending this 1-D list into the empty row list and hence creating the 2-D list.

Python
arr=[]
rows, cols=5,5
for i in range(rows):
    col = []
    for j in range(cols):
        col.append(0)
    arr.append(col)
print(arr)

Output

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

Initializing 2D Array

The provided code demonstrates two different approaches to initializing a 2D array in Python. First, the array arr is initialized using a 2D list comprehension, where each row is created as [0, 0, 0, 0, 0]. The entire array is created as a list of references to the same inner list, resulting in aliasing. Any change made to an element in one row will be reflected in all rows. The code then shows another approach using a nested list comprehension to create the 2D array arr. This method avoids aliasing by creating a new list for each row, resulting in a proper 2D array.

Python
# Python 3 program to demonstrate working 
# of method 1 and method 2.
rows, cols = (5, 5)
# method 2 1st approach
arr = [[0]*cols]*rows
# lets change the first element of the 
# first row to 1 and print the array
arr[0][0] = 1

for row in arr:
    print(row)

# method 2 2nd approach
arr = [[0 for i in range(cols)] for j in range(rows)]

# again in this new array lets change
# the first element of the first row 
# to 1 and print the array
arr[0][0] = 1
for row in arr:
    print(row)

Output

[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]

Explanation:

We expect only the first element of the first row to change to 1 but the first element of every row gets changed to 1 in method 2a. This peculiar functioning is because Python uses shallow lists which we will try to understand.
In method 1a, Python doesn’t create 5 integer objects but creates only one integer object, and all the indices of the array arr point to the same int object as shown.


If we assign the 0th index to another integer say 1, then a new integer object is created with the value of 1 and then the 0th index now points to this new int object as shown below

Similarly, when we create a 2d array as “arr = [[0]*cols]*rows” we are essentially extending the above analogy. 

  1. Only one integer object is created. 
  2. A single 1d list is created and all its indices point to the same int object in point 1. 
  3. Now, arr[0], arr[1], arr[2] …. arr[n-1] all point to the same list object above in point 2.

The above setup can be visualized in the image below.

Now lets change the first element in first row of “arr” as arr[0][0] = 1

  • arr[0] points to the single list object we created we above.(Remember arr[1], arr[2] â€Ķarr[n-1] all point to the same list object too).
  • The assignment of arr[0][0] will create a new int object with the value 1 and arr[0][0] will now point to this new int object.(and so will arr[1][0], arr[2][0] â€Ķ arr[n-1][0])

This can be clearly seen in the below image. 


So when 2d arrays are created like this, changing values at a certain row will affect all the rows since there is essentially only one integer object and only one list object being referenced by the all the rows of the array.

As you would expect, tracing out errors caused by such usage of shallow lists is difficult. Hence the better way to declare a 2d array is 

Python
rows, cols = (5, 5)
print([[0 for i in range(cols)] for j in range(rows)])

Output

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

This method creates 5 separate list objects, unlike method 2a. One way to check this is by using the ‘is’ operator which checks if the two operands refer to the same object. 

Python
rows, cols = (5, 5)

# method 2 2nd approach
arr = [[0 for i in range(cols)] for j in range(rows)]

# check if arr[0] and arr[1] refer to
# the same object
print(arr[0] is arr[1]) # prints False

# method 2 1st approach
arr = [[0]*cols]*rows

# check if arr[0] and arr[1] refer to the same object prints True because there is only one
#list object being created.
print(arr[0] is arr[1])

Output

False
True

Python | Using 2D arrays/lists the right way – FAQs

How to convert 2D array to list in Python?

If you have a 2D array represented as a list of lists and you want to flatten it into a single list:

# Example 2D array (list of lists)
two_d_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Convert 2D array to a single list
flat_list = [item for sublist in two_d_array for item in sublist]

print(flat_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

How to store 2D array in Python list?

You can directly initialize a 2D array as a list of lists:

# Initialize a 2D array (list of lists)
two_d_array = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Accessing elements in the 2D array
print(two_d_array[0][0]) # Accessing the element at row 0, column 0 (outputs: 1)

How do you navigate a 2D list in Python?

To navigate or iterate through a 2D list, you can use nested loops:

for row in two_d_array:
for element in row:
print(element, end=" ")
print()

This will print each element of the 2D list row by row.

How to get data from 2D array in Python?

You can access specific elements or slices from a 2D array using indexing:

# Accessing specific element
element = two_d_array[1][2] # Accessing element at row 1, column 2 (outputs: 6)

# Accessing entire row
row = two_d_array[0] # Accessing entire first row (outputs: [1, 2, 3])

# Accessing entire column (using list comprehension)
column = [row[1] for row in two_d_array] # Accessing second column (outputs: [2, 5, 8])

How to read data from 2D array?

To read or access data from a 2D array, use indexing to retrieve specific elements, rows, or columns as needed.

How to get value in 2D array?

Use double indexing (array[row_index][column_index]) to get the value at a specific position in the 2D array.



Previous Article
Next Article

Similar Reads

Cropping an Image in a circular way using Python
In this article, we will learn to crop an image circularly using a pillow library. Cropping an image circularly means selecting a circular region inside an image and removing everything outside the circle. Approach: If you have an L mode image, the image becomes grayscale. So we create a new image with mode "L".An image is created with a white circ
2 min read
Python List Comprehension | Three way partitioning of an array around a given range
Given an array and a range [lowVal, highVal], partition the array around the range such that array is divided in three parts. 1) All elements smaller than lowVal come first. 2) All elements in range lowVal to highVal come next. 3) All elements greater than highVal appear in the end. The individual elements of three sets can appear in any order. Exa
3 min read
Change your way to put logic in your code - Python
Aren't you bored coding in the same traditional logic over these years. It's time to bring some differences. Well, be it any programming language. When we are asked to do some sort of basic programming exercises like sorting, searching, prime number checking, etc. we are all driven towards the same boat, which is the same coding logic. Now, we are
5 min read
Different way to create a thread in Python
A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an Operating System. There are various ways to create a thread: 1) Create a Thread without using an Explicit function: By importing the module and creating the Thread class object separately we can easily
4 min read
How to Perform a One-Way ANOVA in Python
One-Way ANOVA in Python: One-way ANOVA (also known as "analysis of variance") is a test that is used to find out whether there exists a statistically significant difference between the mean values of more than one group. Hypothesis involved: A one-way ANOVA has the below given null and alternative hypotheses: H0 (null hypothesis): Ξ1 = Ξ2 = Ξ3 = â€Ķ
2 min read
Bidirectional Hash table or Two way dictionary in Python
We know about Python dictionaries in a data structure in Python which holds data in the form of key: value pairs. In this article, we will discuss the Bidirectional Hash table or Two-way dictionary in Python. We can say a two-way dictionary can be represented as key ⇐⇒ value. One example of two-way dictionaries is: Example: dict={ 1 : 'Apple' , 2 :
3 min read
Python Comments: Importance, Types and Correct Way to Use
Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program. # I am single line comment """ Multi-line comment used print("Python Comments") """ Comments enhance the readability of the code and help the programmers to understand the code very carefully.
4 min read
What is a clean and Pythonic way to have multiple constructors in Python?
Python does not support explicit multiple constructors, yet there are some ways to achieve multiple constructors. We use Python's inbuilt __init__ method to define the constructor of a class. It tells what will the constructor do if the class object is created. If multiple __init__ methods are written for the same class, then the latest one overwri
7 min read
Best way to learn python
Python is a versatile and beginner-friendly programming language that has become immensely popular for its readability and wide range of applications. Whether you're aiming to start a career in programming or just want to expand your skill set, learning Python is a valuable investment of your time. This article guide to help you start your journey
11 min read
Most Efficient Way To Find The Intersection Of A Line And A Circle in Python
To make an efficient algorithm to find the intersection of a line and a circle, we need to understand what lines and circles are and how we can mathematically represent and calculate them in Python. Prerequisites LineCirclesQuadratics EquationsSolving a Quadratic EquationQuadratic Formula/Sridharacharya FormulaMathematical ApproachTo find the inter
8 min read
The Best Way to Add N Seconds to datetime.time in Python
Adding a specified number of seconds to a datetime.time object in Python can be a bit tricky because of the datetime.time class does not support date-related operations such as adding seconds directly. While we can't directly add seconds to a datetime.time object, we can achieve this by combining it with a datetime.date object and using datetime.ti
3 min read
Best Way To Start Learning Python - A Complete Roadmap
Python...The world's fastest-growing and most popular programming language not just amongst software engineers but also among mathematicians, data analysts, scientists, accountants, network engineers, and even kids! because it's a very beginner-friendly programming language. People from different disciplines use Python for a variety of different ta
10 min read
Fastest way to Convert Integers to Strings in Pandas DataFrame
Pandas - An open-source library which is used by any programmer. It is a useful library that is used for analyzing the data and for manipulating the data. It is fast, flexible, and understandable, handles the missing data easily. Not only it provides but also enhances the performance of data manipulation and analysis tools with the powerful data st
2 min read
Plotting In A Non-Blocking Way With Matplotlib
When we plot a graph with Matplotlib, by default the execution of the code is stopped/blocked when it is viewed/drawn until the view window is closed. However, in certain cases, one may want to remove this blocking behavior and see the graph as soon as it is plotted or updated without blocking the program execution. This article addresses this issu
5 min read
Argparse: Way to include default values in '--help'?
Argparse in Python allows you to create user-friendly command-line interfaces. By including default values in the --help output, you can make your script's behavior more transparent. There are several ways to achieve this, including using argparse.ArgumentDefaultsHelpFormatter and custom help formatters. Include default values in '--help'Below are
2 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
What is the fastest way to drop consecutive duplicates a List[int] column?
Handling data efficiently is a critical task in many programming and data analysis scenarios. One common problem is dealing with consecutive duplicates in lists, especially when working with columns of data in formats like CSV files or databases. This article explores the fastest ways to drop consecutive duplicates from a List[int] column, ensuring
3 min read
What is a Pythonic Way for Dependency Injection?
Design pattern Dependency Injection (DI) achieves Inversion of Control (IoC) between classes and their dependencies. DI increases testability and modularity by externalizing the building and control of dependencies. This post will investigate DI from a Pythonic standpoint with an eye toward best practices and pragmatic solutions. Understanding Depe
4 min read
What is the Recommended Way for Retrieving Row Numbers (Index) for Polars?
Polars is a fast DataFrame library implemented in Rust and designed to process large data sets efficiently. One of the common tasks while handling data frames is retrieving row numbers (indices) for various operations. This article explores the recommended ways to retrieve row numbers in Polars, providing clear examples for each method. Prerequisit
4 min read
Right and Left Hand Detection Using Python
In this article, we are going to see how to Detect Hands using Python. We will use mediapipe and OpenCV libraries in python to detect the Right Hand and Left Hand. We will be using the Hands model from mediapipe solutions to detect hands, it is a palm detection model that operates on the full image and returns an oriented hand bounding box. Require
5 min read
Right Click menu using Tkinter
Python 3.x comes bundled with the Tkinter module that is useful for making GUI based applications. Of all the other frameworks supported by Python Tkinter is the simplest and fastest. Tkinter offers a plethora of widgets that can be used to build GUI applications along with the main event loop that keeps running in the background until the applicat
5 min read
How to compute the eigenvalues and right eigenvectors of a given square array using NumPY?
In this article, we will discuss how to compute the eigenvalues and right eigenvectors of a given square array using NumPy library. Example: Suppose we have a matrix as: [[1,2], [2,3]] Eigenvalue we get from this matrix or square array is: [-0.23606798 4.23606798] Eigenvectors of this matrix are: [[-0.85065081 -0.52573111], [ 0.52573111 -0.85065081
2 min read
turtle.right() method in Python
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. turtle.right() The turtle.right() method is used to change the direction of the turtle by the value of the argument that it takes. It
2 min read
Python Pandas - Check if the interval is open on the left and right side
In pandas Interval.closed_left and Interval.closed_right attributes are used to check if the interval is open on left and right side. Intervals: Closed interval : closed ='both' represents closed interval. The closed interval contains its endpoints. it is of the form [a,b] and it has the condition a<=x<=b.Open interval: closed =' neither' rep
2 min read
Choosing the Right IDE for Python Development: A Comparison
Python, being one of the most popular programming languages, has a rich ecosystem of development environments. Selecting the right Integrated Development Environment (IDE) for Python development can greatly enhance your productivity, streamline coding workflows, and improve debugging processes. Different IDEs cater to different types of developers,
5 min read
PyQt5 - Check Box with Indicator at right side
In this article we will see how to set the indicator to the right of check box. Check box basically have two components first is indicator and other is the label by default indicator is at the left hand side. In order to make the indicator at the right hand side we have to change its layout direction from left to right side. In order to do this we
2 min read
PyQt5 – Radio button indicator at right side
In this article we will see how to make indicator of radio button at the right side. By default when we create a radio button its indicator is at the left side. Indicator of radio button is the round check-able part which indicates it is checked or not. Below is normal radio button vs the radio button whose indicator is at right side. In order to m
2 min read
PyQt5 – Check if alignment of radio button is left to right
In this article we will see how to check if the alignment of radio button is left to right or not. By default alignment of radio button is left to right although with the help of setLayoutDirection we can change its alignment. Left to right direction is basically tells that indicator is on the left side and text part is on the right side. Overview
2 min read
PyQt5 – Check if layout direction of radio button is right to left
In this article we will see how to check if the layout direction of radio button is right to left or not. By default alignment of radio button is left to right although with the help of setLayoutDirection we can change its alignment. Right to left direction is basically tells that indicator is on the right side and text part is on the left side. Ov
2 min read
PyQt5 QSpinBox - Checking if value is at right side
In this article we will see how we can check if the value appear in the right side of spin box or not, when we create spin box the value is at the left hand side in order to make the value in right we have to set its alignment flag to right. In order to do this we will use alignment method. Syntax : spin_box.alignment() Argument : It takes no argum
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg