0
import os;
import sys;
import random;


particle_list = [[-1, float(1)/100]] * 20;
print particle_list;

for i in range(0, len(particle_list)):

    a = random.randint(0, 10);
    particle_list[i][0] = a;
    print str(a);

    print particle_list[i][1];
    particle_list[i][1] *= 2;
    print particle_list[i][1];
    print;

if you print out the result, in the particle_list, all the results are same. Can anyone help ?

Ocean
  • 1
  • 1
  • this is the result from my terminal: [[6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76], [6, 10485.76]] – Ocean Feb 28 '17 at 03:57
  • When making the list, try list comprehension. `particle_list = [[random.randint(0, 10), float(2)/100] for i in range(20)]` – spazhead Feb 28 '17 at 04:04
  • I am not trying to expand the list. so could you kindly tell me what's wrong with the code i attached in the question? it seems a very standard task – Ocean Feb 28 '17 at 04:10
  • I ran your code. Initially it gives `[[-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01], [-1, 0.01]]` as expected and then random staff. – Nurjan Feb 28 '17 at 04:12
  • 1
    Ditch the semicolons. Python isn't C. Also -- you seem to be creating a list of list aliases. `particle_list = [[-1, float(1)/100]] * 20` doesn't do what you think it does. – John Coleman Feb 28 '17 at 04:16
  • if you print particle_list after the code, then it has the issue – Ocean Feb 28 '17 at 04:17

1 Answers1

2

Change your particle_list declaration to:

particle_list = [[-1, float(1)/100] for i in range(20)]

The way you are currently generating your list creates the rest of the items in the list as references to the first item. This code will generate different lists for each item in the list, not references.

It is also recommended you do not use semi-colons in your code, as they are not very pythonic

spazhead
  • 304
  • 3
  • 14