0

How would I reassign a value in a list every time i called it. For example in:

def randomfunction():
    var1 = random.randint(1,10)
    return var1

list1 = [None,None,None,None]

list1[1] = randomfunction()

How do I make the list[1] value equal to the randomfunction() rather than just one value returned by the function.

i.e everytime I call list[1] there is a new value from randomfunction().

Danny Herbert
  • 2,002
  • 1
  • 18
  • 26

2 Answers2

0

What do you think of this solution:

import random

class specli(list):
    def __init__(self):
        self.append(random.randint(1,10))
    def __getitem__(self,i):
        if i==0:
            return random.randint(1,10)
        elif i<len(self):
            return super(specli,self).__getitem__(i)
        else:
            [][i]

L = specli()
print L
L.append('B')
print L
L.append('C')
print L
print '-------------'
print 'L[0] :',L[0]
print 'L[1] :',L[1]
print 'L[2] :',L[2]
print 'L[3] :',L[3]

result

[2]
[2, 'B']
[2, 'B', 'C']
-------------
L[0] : 2
L[1] : B
L[2] : C
L[3] :

Traceback (most recent call last):
  File "I:\potoh\ProvPy\quichotte.py", line 24, in <module>
    print 'L[3] :',L[3]
  File "I:\potoh\ProvPy\quichotte.py", line 12, in __getitem__
    [][i]
IndexError: list index out of range
eyquem
  • 26,771
  • 7
  • 38
  • 46
0

To reassign the value, you just need to keep calling the function and you'll most likely receive a different number every time you call it.

For example:

   import random 

    def randomfunction():
        var1 = random.randint(1,10)
        return var1

    list1 = [None,None,None,None]

    list1[1] = randomfunction()
    print(list1)


    list1[1] = randomfunction()
    print(list1)


    list1[1] = randomfunction()
    print(list1)

I received an output of:

>>> 
[None, 1, None, None]
[None, 6, None, None]
[None, 9, None, None]

So each time I called the function and assigned it to list1[1], I got a different value.

83457
  • 203
  • 1
  • 11
  • This works perfectly! Thanks! i also managed to make it work by assigning `randomfunction` (no brackets, not called) to `list[1]` then calling `list[1]()`. – Danny Herbert Jan 05 '14 at 20:16
  • @gjttt1 Glad I could help. I'll have to check that claim of yours later when I have time, because wouldn't randomfunction be an undefined variable? – 83457 Jan 06 '14 at 07:25
  • Thats what i though but [This](http://stackoverflow.com/questions/10354163/assigning-a-function-to-a-variable) is where I found out the other way. It just assigns the actual Function (like when you see it with its memory location) to the 1st index of the list and then you can call it from that. – Danny Herbert Jan 06 '14 at 18:38