0

how can I randomly select an element from a 2d array and then add to it?

amount_to_add = 13
my_array = [[0,0],[0,0],[0,0]]

I want to randomly add 13 to one of the elements so it'd look like

my_array = [[0,0],[0,13],[0,0],[0,0]]
1
  • Is the output my_array supposed to have an additional list in it? Or should it be the same length as the original my_array? Commented Nov 13, 2013 at 23:58

2 Answers 2

2
import random

my_array[random.randrange(len(my_array))].append(amount_to_add)

Just that simple.

Demo:

>>> my_array = [[0],[0],[0],[0]]
>>> my_array[random.randrange(len(my_array))].append(amount_to_add)
>>> my_array[random.randrange(len(my_array))].append(amount_to_add)
>>> my_array
[[0], [0], [0, 10], [0, 10]]

Edit: Turns out i misunderstood the question. Here is how to add:

>>> my_array = [[0,0],[0,0],[0,0],[0,0]]
>>> random.choice(my_array)[random.randrange(len(choice))] += amount_to_add
>>> my_array
[[0, 10], [0, 0], [0, 0], [0, 0]]
>>> random.choice(my_array)[random.randrange(len(choice))] += amount_to_add
>>> my_array
[[0, 10], [0, 0], [0, 0], [0, 10]]
Sign up to request clarification or add additional context in comments.

1 Comment

This adds a new element to a random sublist. Not what he asked for.
1

This works:

>>> from random import choice, randint
>>> amount_to_add = 13
>>> my_array = [[0,0],[0,0],[0,0]]
>>> element = choice(my_array)
>>> element[randint(0, len(element)-1)] += amount_to_add
>>> my_array
[[13, 0], [0, 0], [0, 0]]
>>> my_array = [[0,0],[0,0],[0,0]]
>>> element = choice(my_array)
>>> [randint(0, len(element)-1)] += amount_to_add
>>> my_array
[[0, 0], [0, 0], [0, 13]]
>>>

It randomly chooses an element in my_array, randomly chooses an index on that element, and then adds amount_to_add to the item at that index.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.