0

I'm kinda new to python... So I've been strugling with a problem for a while and after doing a huge research I did not find solution so I decided to ask here :).

So the code that is explaining my problem:

test = []
solutions = []

i = 0
while i < 100:
    for i in range(0, 64):
        pos = random.randrange(0, 64)
        test.append(pos)
    solutions.append(test)
    test.clear()
    i += 1

So I want to add a copy of a table to another table everytime the loop goes and then clean the table named test. The problem is I don't know how to create a copy of list each time the loop goes. So I'm getting list of empty lists :(

I tried with copy.copy or copy.deepcopy but that didn't work.

That is my first question here so sorry for any "errors" also I'm not native english speaker but I hope you will be able to understand me.

Elvenpath
  • 1
  • 2
  • 4
  • Not sure what you want to do here, but the `while` loop will never end. Even adding `i += 1` will not be enough (though it is necessary). You have to use 2 distincts names for the `i` in the `while` loop and the on in the `for` loop, or use `for _ in range(0, 64)` for instance – zaphodef Apr 01 '16 at 19:14
  • Yea I'll edit my question – Elvenpath Apr 01 '16 at 19:18

3 Answers3

0

You can append duplicates by calling the list constructor

solutions.append(list(test))
John
  • 13,197
  • 7
  • 51
  • 101
0

if you want clean simply dont use test.clear()

use:

test = []

you should remove the test.clear(), and change <100 of while because is infinite

import random
test = []
solutions = []

i = 0
while i < 100:
    for i in range(0, 64):
        pos = random.randrange(0, 64)
        test.append(pos)
    solutions.append(test)
Milor123
  • 537
  • 4
  • 20
0

You can do copy the list like:

solutions.append(test[:])

And to empty it, since there is no empty method, you can just reassign it to a new empty list:

test = []

Like Zaphod mentioned, your while loop never finished, since you were never updating the value of i, plus is was being assigned in the inner for loop anyway. Why not use two nested for loops? (the underscore is just a var placeholder signifying the value is not used)

import random

test = []
solutions = []

for _ in range(0, 100):
    for i in range(0, 64):
        pos = random.randrange(0, 64)
        test.append(pos)
    solutions.append(test[:])
    test = []
print solutions
heinst
  • 8,520
  • 7
  • 41
  • 77
  • This worked for me! Thanks! @Edit I wanted list of "new lists" not list of "the same list" So yea you answer is what I was looking for. Thanks again : ) – Elvenpath Apr 01 '16 at 19:35