Search code examples
pythonlistvariablesrandomstore

Storing items in a list for python


I am new to python and would like to ask a simple question.

I am trying to get this program to loop and every time it loops, it should store a variable in a list.

Please help

This is my code so far:

import random
for x in range(1,100):
    q=random.randint(0,99)
    w=random.randint(0,99)
    e=q*w
    q=[]#This is the list
    print '%s * %s = %s'%(q,w,e)

Solution

  • You need to define the list outside of the loop, and append to it within the loop.

    import random
    
    # Define your list
    l = []
    for x in range(1,100):
        q=random.randint(0,99)
        w=random.randint(0,99)
        e=q*w
        # Append the result to your list
        l.append(e)
        print '%s * %s = %s'%(q,w,e)
    
    print 'The list becomes: %s' % l