user2509830
user2509830

Reputation: 93

Manipulating Python Lists

I have a list of 100 elements. I am trying to create a function that will make 300 copies of that list and then store those copies into a blank list. I then need the function to choose an indexed value at random from each copied list. So, it might choose the 25th index value in the first copied list, and then it might choose the 60th index value in the next copied list. Then, the index of the value is an argument of a pre-defined function. The problem is that my copied lists are not being manipulated.

my code is as follows:

def condition_manipulate(value):
    list_set=[]                  #this is the list in which the copied lists will go
    for i in range(0,value):
        new_list=initial_conditions[:]    #initial_conditions is the list to be copied
        list_set.append(new_list)
        for i in list_set:           #My confusion is here. I need the function to choose
            for j in i:              #A random value in each copied list that resides
                 x=random.choice(i)  #In list_set and then run a predefined function on it.
                 variable=new_sum(i.index(x)
                 i[i.index(x)]=variable
    return list_set

#running condition_manipulate(300) should give me a list with 300 copies of a list
#Where a random value in each list is manipulated by the function new_sum

I have tried almost everything. What am I doing wrong? Any Help will be appreciated. Thanks.

Upvotes: 0

Views: 199

Answers (2)

Dan Gittik
Dan Gittik

Reputation: 3860

Try:

import random

def condition_manipulate(value):
    list_set=[]
    for i in range(value):
        new_list=initial_conditions[:]
        i=random.choice(range(len(initial_conditions)))
        new_list[i]=new_sum(new_list[i])
        list_set.append(new_list)
    return list_set

Upvotes: 1

Steve Barnes
Steve Barnes

Reputation: 28415

If you really need copies of lists rather than shallow copies then you need to:

import copy

oldlist = [.....]
newlist = copy.deepcopy(oldlist)

Otherwise all the copies are really the same list.>>> o = [1, 2, 3]

>>> n = o
>>> n.append(4)
>>> o
[1, 2, 3, 4]
>>> n = copy.deepcopy(o)
>>> n
[1, 2, 3, 4]
>>> n.append(5)
>>> n
[1, 2, 3, 4, 5]
>>> o
[1, 2, 3, 4]
>>> 

Upvotes: 1

Related Questions