Python Forum
Adding random numbers to each item in a 2d list.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding random numbers to each item in a 2d list.
#1
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
Reply
#2
Why not use
for sublist in greeting:
    sublist.append(randint(0, 9))
?
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020