Creating a 2D list using list comprehension in Python is done with nested list comprehensions. The correct syntax is:

rows, cols = 5, 5
matrix = [[0 for _ in range(cols)] for _ in range(rows)]

This creates a 5×5 2D list where each inner list is a separate object, avoiding unintended shared references.

Key Points:

  • Inner comprehension [0 for _ in range(cols)] creates a new list for each row.

  • Outer comprehension for _ in range(rows) repeats this process for the number of rows.

  • This method ensures each row is independent and safe for modification.

Common Mistake:

Avoid using [[0] * cols] * rows — this creates multiple references to the same inner list, causing aliasing. Updating one element affects all rows.

Examples:

  • Initialize with zeros:

    matrix = [[0 for _ in range(4)] for _ in range(3)]
  • Initialize with values:

    matrix = [[i * 4 + j for j in range(4)] for i in range(3)]
  • Modify elements conditionally:

    matrix = [[x * 2 if x % 2 == 0 else x for x in row] for row in matrix]
  • Flatten a 2D list:

    flat = [item for row in matrix for item in row]

Use nested list comprehensions for clean, readable, and efficient 2D list creation and manipulation.

You have the order of your loops swapped; they should be ordered in the same way they would be nested, from left to right:

[int(x) for line in data for x in line.split()]

This loops over data first, then for each line iteration, iterates over line.split() to produce x. You then produce one flat list of integers from these.

However, since you are trying to build a list of lists, you need to nest a list comprehension inside another:

Cordi1 = [[int(i) for i in line.split()] for line in data]

Demo:

>>> data = '''\
... 2 3 4 5 6 3
... 1 2 2 4 5 5
... 1 2 2 2 2 4
... '''.splitlines()
>>> [int(x) for line in data for x in line.split()]
[2, 3, 4, 5, 6, 3, 1, 2, 2, 4, 5, 5, 1, 2, 2, 2, 2, 4]
>>> [[int(i) for i in line.split()] for line in data]
[[2, 3, 4, 5, 6, 3], [1, 2, 2, 4, 5, 5], [1, 2, 2, 2, 2, 4]]

If you wanted a multidimensional numpy array from this, you can either convert the above directly to an array or create an array from the data then reshape:

>>> import numpy as np
>>> np.array([[int(i) for i in line.split()] for line in data])
array([[2, 3, 4, 5, 6, 3],
       [1, 2, 2, 4, 5, 5],
       [1, 2, 2, 2, 2, 4]])
>>> np.array([int(i) for line in data for i in line.split()]).reshape((3, 6))
array([[2, 3, 4, 5, 6, 3],
       [1, 2, 2, 4, 5, 5],
       [1, 2, 2, 2, 2, 4]])
Answer from Martijn Pieters on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-using-2d-arrays-lists-the-right-way
Using 2D arrays/lists in Python - GeeksforGeeks
Functionally equivalent to nested list comprehension. Useful for step-by-step construction. The code below, compares two ways of initializing a 2D list in Python. Using list multiplication ([[0]*cols]*rows) creates multiple references to the same inner list, causing aliasing where changes affect ...
Published   December 20, 2025
Discussions

Understanding list comprehensions and Numpy
Numpy arrays aren't really meant to be built like this. It would be better to create a list, keep appending to it, and when you're done turn it into an array. I'd also expect this to be more efficient since lists are meant to have a fast append, and I'd guess that np.append is not O(1), or rather O(length of appended list). Also yes, merging numpy arrays (I use merging very generally here) is annoying because of dimensions and the number of functions there are to do it (it gets confusing). I wouldn't say I use numpy a lot, but it's definitely a pain to work with. More on reddit.com
🌐 r/learnpython
5
2
August 6, 2021
How do nested list comprehensions work?
It's really no different from normal list comprehensions, except the element happens to involve a list comprehension. [[x | x <- xs, even x] | xs <- xxs] is the same as let evens list = [x | x <- list, even x] in [evens xs | xs <- xxs] More on reddit.com
🌐 r/haskell
6
5
December 10, 2021
python - Using List Comprehension To Repeat Entries in 2D Array - Stack Overflow
1 Error in Creating a 2d array via plain for loop iteration but not if created via list comprehension More on stackoverflow.com
🌐 stackoverflow.com
How to produce the sum of two 2D lists by element?
You might want to flatten your lists with itertools.chain.from_iterable. Then you can simply use the sum() as in your example. If you want to keep the 2D structure, maybe numpy can help. More on reddit.com
🌐 r/learnpython
30
14
May 6, 2015
🌐
DEV Community
dev.to › kalebu › a-guide-to-python-list-comprehension-28d3
A guide to Python list comprehension - DEV Community
May 22, 2022 - You can also use list comprehension to flatten the 2D array to a single 1D array by iterating on all elements on a list.
🌐
GeeksforGeeks
geeksforgeeks.org › python › nested-list-comprehensions-in-python
Nested List Comprehensions in Python - GeeksforGeeks
July 5, 2025 - Explanation: This code builds a 5x5 matrix (list of lists), where each row contains numbers from 0 to 4 using nested loops. ... Explanation: A more concise version of the same logic, the inner loop [c for c in range(5)] creates each row and the outer loop repeats it 5 times. ... m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] odds = [] for r in m: for e in r: if e % 2 != 0: # Check if element is odd odds.append(e) print(odds) ... Explanation: This loops through a 2D list and adds all odd numbers to a new list odds.
🌐
Quora
quora.com › What-is-the-syntax-for-declaring-a-2D-array-in-Python-using-a-list-comprehension
What is the syntax for declaring a 2D array in Python using a list comprehension? - Quora
Answer (1 of 3): [code]twoD_array = [[0 for i in range(num_columns)] for j in range(num_rows)] [/code]The above code makes a 2-dimensional array named twoD_array filled with zeros and size of num_rows x num_columns. A cleaner way to do this is make a helper method, probably something like this: ...
🌐
W3Schools
w3schools.com › python › python_lists_comprehension.asp
Python - List Comprehension
The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list: ... The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome: ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › understanding list comprehensions and numpy
r/learnpython on Reddit: Understanding list comprehensions and Numpy
August 6, 2021 -

Hi, I've got this list comprehension that's working exactly as I want it to, but I'm trying to understand and replicate what it's doing by converting it into a for loop.

Here's the list comprehension -

predictions = np.array([tree.predict(X) for tree in self.trees])
swapped = np.swapaxes(predictions, 0, 1)

Here's the for loop I'm using to try replicate and understand this process -

predictions = np.array([])
for tree in self.trees:
    predictions = np.append([predictions], [[tree.predict(X)]], axis=0)
swapped = np.swapaxes(predictions, 0, 1)

With the for loop I'm getting all kinds of errors to do with it's dimensionality depending on how I implement the square brackets. Such as -

numpy.AxisError: axis2: axis 1 is out of bounds for array of dimension 1

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

It looks like it should be doing the same thing, but I'm clearly doing something wrong.

Any help or pointers would be great!

Thanks

🌐
AskPython
askpython.com › home › how to replace a for loop with list comprehension in a 2d matrix?
How to Replace a For Loop With List Comprehension in a 2D Matrix? - AskPython
May 25, 2023 - We are creating a 2D matrix using the numpy library’s array method. The matrix is made up of 2 rows and 3 columns and contains 6 elements. This matrix is named mat. It is printed in the next line. We are using a for loop to get through every row in the matrix and every element in the row. The element at each position is printed. ... The list comprehension follows the same code but doesn’t need the code spread across multiple lines.
🌐
Python documentation
docs.python.org › 3 › tutorial › datastructures.html
5. Data Structures — Python 3.14.3 documentation
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses ...
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › 2d array in python
Comprehensive Guide to 2D Arrays in Python: Creation, Access, and Use
November 11, 2024 - In a 2-D list, each element is identified using two indices: one for the row and another for the column. There are various methods to create a 2-D list. Let's explore how to create a 2d list Python and populate it.
🌐
Agnostic Development
agnosticdev.com › content › how-use-python-list-comprehensions
How to Use Python List Comprehensions | Agnostic Development
November 23, 2018 - If you have ever wanted to use Python list comprehensions, but were unsure of the syntax or exactly how they worked, then this tutorial is aimed at you. This tutorial will teach you how to use Python list comprehensions to create simple lists, 2d matrices, and even lists.
🌐
Python Central
pythoncentral.io › how-to-initialize-a-2d-list-in-python
How to initialize a 2D List in Python? | Python Central
December 29, 2021 - Python offers various techniques for initializing a 2D list in Python. List Comprehension is used to return a list.
🌐
Reddit
reddit.com › r/haskell › how do nested list comprehensions work?
r/haskell on Reddit: How do nested list comprehensions work?
December 10, 2021 -

When list comprehensions contain multiple lists and multiple "such that"s (|), I am not able to understand how the lists are built. For example,

ghci> let xxs = [[1,3,5,2,3,1,2,4,5],[1,2,3,4,5,6,7,8,9],[1,2,4,2,1,6,3,1,3,2,3,6]]  
ghci> [ [ x | x <- xs, even x ] | xs <- xxs]  
[[2,2,4],[2,4,6,8],[2,4,2,6,2,6]]  

and

take 5 [ [ (i,j) | i <- [1,2] ] | j <- [1..] ]
[[(1,1),(2,1)], [(1,2),(2,2)], [(1,3),(2,3)], [(1,4),(2,4)], [(1,5),(2,5)]]

and

[(i, j) | i <- [2..4]] | j <- [3..5]]
[[(2,3),(3,3),(4,3)],[(2,4),(3,4),(4,4)],[(2,5),(3,5),(4,5)]]

And also, if I wanted to make a triply-nested list comprehension, how would I do that?

🌐
GeeksforGeeks
geeksforgeeks.org › python-using-2d-arrays-lists-the-right-way
Python | Using 2D arrays/lists the right way - GeeksforGeeks
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.
Published   June 20, 2024
🌐
Carnegie Mellon University
cs.cmu.edu › ~112-f24 › notes › notes-2d-lists.html
2d Lists
# still a copy, but cleaner with a list comprehension! a = [ [ 1, 2, 3 ] , [ 4, 5, 6 ] ] col = 1 colList = [ a[i][col] for i in range(len(a)) ] print(colList) ... # 2d lists do not have to be rectangular a = [ [ 1, 2, 3 ] , [ 4, 5 ], [ 6 ], [ 7, 8, 9, 10 ] ] rows = len(a) for row in range(rows): cols = len(a[row]) # now cols depends on each row print("Row", row, "has", cols, "columns: ", end="") for col in range(cols): print(a[row][col], " ", end="") print()
🌐
Scribd
scribd.com › document › 543748646 › Python-2D-lists-CN
Python 2D Lists CN | PDF | Computer Science
JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Stack Abuse
stackabuse.com › python-how-to-flatten-list-of-lists
Python: How to Flatten a List of Lists
September 20, 2023 - Flattening a list of lists entails converting a 2D list into a 1D list by un-nesting each list item stored in the list of lists - i.e., converting [[1, 2, 3], [4, 5, 6], [7, 8, 9]] into [1, 2, 3, 4, 5, 6, 7, 8, 9] . The process of flattening can be performed using nested for loops, list comprehensions, recursion, built-in functions or by importing libraries in Python depending on the regularity and depth of the nested lists.
🌐
Sentry
sentry.io › sentry answers › python › define a two-dimensional array in python
Define a two-dimensional array in Python | Sentry
June 15, 2023 - The following code will create ... this operation. To create a 2D array without using numpy, we can initialize a list of lists using a list comprehension....