Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D lists generation Python

Tags:

python

loops

list

I know that to generate a list in Python you can use something like:

l = [i**2 for i in range(5)]

instead of using for loop like:

l = []
for i in range(5):
    l.append(i**5)

Is there a way to do 2D lists without using for loops like this:

map = [[]]

for x in range(10):
    row = []
    for y in range(10):
        row.append((x+y)**2)
    map.append(row)

Is there any other alternatives to represent 2D arrays in Python ?

like image 995
user1513100 Avatar asked Jan 31 '26 21:01

user1513100


1 Answers

Use a list comprehension here too:

>>> [ [(x+y)**2 for y in range(10)] for x in range(10)]
[[0, 1, 4, 9, 16, 25, 36, 49, 64, 81], [1, 4, 9, 16, 25, 36, 49, 64, 81, 100], [4, 9, 16, 25, 36, 49, 64, 81, 100, 121], [9, 16, 25, 36, 49, 64, 81, 100, 121, 144], [16, 25, 36, 49, 64, 81, 100, 121, 144, 169], [25, 36, 49, 64, 81, 100, 121, 144, 169, 196], [36, 49, 64, 81, 100, 121, 144, 169, 196, 225], [49, 64, 81, 100, 121, 144, 169, 196, 225, 256], [64, 81, 100, 121, 144, 169, 196, 225, 256, 289], [81, 100, 121, 144, 169, 196, 225, 256, 289, 324]]
like image 158
Ashwini Chaudhary Avatar answered Feb 03 '26 11:02

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!