1

after I run this little piece of code, it would always return a list that contains exactly same smaller lists...

import time
from random import randint

t = [0,0]
a = []

def rec():
    a.append(t)

for i in range(10):
    t[0] = randint(10,20)
    t[1] = randint(40,500)
    rec()
    time.sleep(.0001)

print a

I get something like this as output, why?

[[17, 134], [17, 134], [17, 134], [17, 134], [17, 134], [17, 134], [17, 134], [17, 134], [17, 134], [17, 134]]

2 Answers2

2

Welcome to the wacky world of mutable vs immutable types!

The short of it is that in Python list's are mutable, meaning references to lists will actually change the original list! You will have to create a new list by doing t = [randint(10,20), randint(40,500)]. That should do the trick for you :)

For more information on mutable vs immutable types refer to this SO Q/A!

I would also recommend not having functions like rec. Try to avoid using globals when you do not need them (they make debugging more difficult than it needs to be). Why not just pass in a parameter? Or just use append inline!

Community
  • 1
  • 1
Michael S Priz
  • 1,116
  • 7
  • 17
  • 1
    But you need to declare it `global` first, otherwise it will just be a local list and won't be the one appended by `rec`. – Peter Wood Aug 21 '15 at 13:34
  • But `t` was already declared in the global scope! The OPs code with my suggestion added works for me :) – Michael S Priz Aug 21 '15 at 14:07
  • thanks! Well because I am using a decorator to limit the speed that rec() runs, so I need to define a function there... – mengqimusic Aug 21 '15 at 15:30
0

How about using list comprehensions - [[randint(10,20), randint(40,500)] for i in range(10)]?

matino
  • 17,199
  • 8
  • 49
  • 58