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 OverflowUnderstanding list comprehensions and Numpy
How do nested list comprehensions work?
python - Using List Comprehension To Repeat Entries in 2D Array - Stack Overflow
How to produce the sum of two 2D lists by element?
Videos
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
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?
if you're just looking to convert your code into a list comprehension then just write your loops in their original order. This way you'll never forget how to get things done using list comprehension.
output = [
_a
for i, _as in enumerate(l)
for _a in _as
for _n in range(n[i])
]
You can use a double list comprehension:
l = [[1,2,3], [4,5,6]]
n = [2, 3]
empty =[i for j in [[a]*f for b,f in zip(l,n) for a in b] for i in j]
print(empty)
Output:
[1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]