Search code examples
pythonlistappendsimulate

How can I append lists with items from another list and leave these empty in a simulation?


Here is my code:

import random
listx = []
ready = 0
listy = []
listz = []

#function

def function(r,s,q):
    listy=[]
    if len(listx)==4 or len(listx)==8:
        listy.append((listx, t))
        print "y", listy

# here it starts:

for t in range(1,25): 

    randomnumber = random.uniform(0.0, 1.0)

    if randomnumber <= 0.5:
        listx.append((t))   
        print "x", listx

    if ready == 0: #condition, lets say: ready is always 0
        function(5,6,8) #this function generates listy from input of listx

    if listy != 0: #if listy is not empy anymore, fill listz with items of listy
            listz.append(listy)
            del listy
            print "z", listz

I have 3 lists; listx, listy and listz. I generate random numbers to listx. If ready==0 (always) I call the function (function(r,s,q)). If a condition (len==4 or 8) is met, the items in the list are appended to listy.

At this point, I would like to add these numbers from listy to listz and leave listy empty again. The items that I transported from listy to listz should be removed from listx.

Does anyone know how to solve this?


Solution

  • I think this may do you want. Changes to your code are indicated with # UPPERCASE COMMENTS.

    import random
    listx = []
    ready = 0
    listy = []
    listz = []
    
    #function
    
    def function(r,s,q):
        global listy  #### ADDED
    
        listy=[]
        if len(listx) in (4, 8):  # STREAMLINED
            listy.append((listx, t))
            print "y", listy
    
    # here it starts:
    
    for t in range(1,25):
    
        randomnumber = random.uniform(0.0, 1.0)
    
        if randomnumber <= 0.5:
            listx.append((t))
            print "x", listx
    
        if ready == 0: # condition, lets say: ready is always 0
            function(5,6,8) # this function generates listy from input of listx
    
        #### REWRITTEN
        if listy: # not empty?
            listz += listy[0][0]  # copy numbers from listy to listz
            del listx[:len(listy[0][0])]  # remove numbers transported from listx
            del listy  # empty listy
            print "z", listz