Reputation: 314
I have a list:
ls = [["a", "b"],
["c", "d"],
["e", "f"]]
I want to change a, c or e to 1. I tried this:
import random
for num, row in enumerate(ls):
r = random.choice(num[0])
r[0] = 1
print(ls)
But I only get:
r = random.choice(num[0])
TypeError: 'int' object is not subscriptable
How can I change a random element from the first column of 2D array?
Upvotes: 0
Views: 94
Reputation: 195408
Chose random number from 0 to len(ls) - 1 and change the first element in the row:
import random
ls = [["a", "b"], ["c", "d"], ["e", "f"]]
random_row = random.randint(0, len(ls) - 1)
ls[random_row][0] = 1
print(ls)
Prints (for example):
[['a', 'b'],
[1, 'd'],
['e', 'f']]
Upvotes: 4