Python Forum

Full Version: Adding random numbers to each item in a 2d list.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Just making this post if anyone happens to be specifically stuck on this problem because as a beginner at coding, it took me some time. Hope this post helps!

from random import randint ##this allows you to use a random integer

greeting = [["hi"],["hello"],["hiya"]] ##just the 2d list

thislistnamedoesntreallymatter = [(x.append(randint(0,9))) for x in greeting] ##the x just refers to the items in the list. x.append, appends(or adds) "randint(0,9)"(random integer within the range of 0-9) to each item within its own list. "for x in greeting" just means for every item in the list greeting.

print(greeting) ##prints the whole list
print(greeting[0][1])##prints the fist randomly generated iteger
I tried my best if there are any mistakes just comment them down below... pls no roast me Tongue
Why not use
for sublist in greeting:
    sublist.append(randint(0, 9))
?