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 ?
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With