Search code examples
pythonlistloopsparticle-system

How do I print an item outside of a loop?


Beginner here,

If I create a loop to create some lists, how would you print a specific list outside of the loop?

This is my code so far:

import random

for i in range(0,5):
  "particle = [mass/posx/posy/velx/vely]"
  posx=random.randint(1,10)
  posy=random.randint(1,10)
  velx=random.randint(-0,0)
  vely=random.randint(-0,0)
  particle=[mass,posx,posy,velx,vely]
  print(particle)

How could I then, for example, print the 3rd list outside of the for i in range ... ?

So its on the lines of

print particle3

Solution

  • Should initalize list outside of loop as you are overiding the list on each iteration

    import random
    particle=[]
    for i in range(5): # you do not need 0 in range
      #"particle = [mass/posx/posy/velx/vely]"
        posx=random.randint(1,10)
        posy=random.randint(1,10)
        velx=random.randint(-0,0)
        vely=random.randint(-0,0)
        particle.append([mass,posx,posy,velx,vely]) # no idea what mass is
    print(particle[2]) # should print third list