1

as the title says I have the problem that I can't do a function, where the list is expanding continuously to some value. I need this for a bigger program I'm writing.

Here are two examples that don't work. first one:

from random import *
import time

A = []

def list_expander(A):
    A = A + [randint(-5,5)]
    print (A)

while True:
    list_expander(A)
    time.sleep(2)

and second one:

from random import *
import time


def list_expander():
    A = []
    A = A + [randint(-5,5)]
    print (A)

while True:
    list_expander()
    time.sleep(2)

thank you for your help!

cretos
  • 27
  • 4
  • your `list_expander` function doesn't do anything, it creates a new list and then discards it as soon as the function terminates. In any case, you should use `.append` here. That is what it is for. – juanpa.arrivillaga Nov 18 '19 at 19:13
  • 1
    list_expander won't extend the list, it reinitializes A it every time it's called – Marsilinou Zaky Nov 18 '19 at 19:13

3 Answers3

1
from random import *
import time
def list_expander(A):
    A.append(randint(-5,5))
    print (A)
    return A
A=[]
while True:
    A=list_expander(A)
    time.sleep(2)


Eshonai
  • 121
  • 5
1

To modify an immutable item (for example a list), you can use its mutating methods (.append() in this case). So in your first example if you replace A = A + [randint(-5,5)] with A.append(randint(-5, 5)), you should get what you want. Your first example does not work because the function creates a "new" A every time you call it, it does not "change" the outside list A. The second one obviously won't work either because of the same reason, and also the fact that it reinitialises A with an empty list every time it's called (A = []).

All in all, I would rewrite your code as:

from random import randint
from time import sleep

A = []

def list_expander(A):
    A.append(randint(-5,5))
    print(A) # are you sure you need this?

while True:
    list_expander(A)
    time.sleep(2)

You can read How do I pass a variable by reference? to better understand why your first example doesn't change the list A.

mlg556
  • 419
  • 3
  • 13
0

As far as I understand you want to keep appending to the list, so you will have to return it so that you can append to it (extend) again next iteration.

from random import *
import time

def list_expander(A):
    A.append(randint(-5,5))
    print (A)

A = []
while True:
    list_expander(A)
    time.sleep(2)
    x+=1

This code will print

[1]
[1, -5]
[1, -5, 4]
[1, -5, 4, 5]
[1, -5, 4, 5, 2]

Another approach you can take is to have the list as a global variable but keep in mind it's bard practice.

Marsilinou Zaky
  • 1,038
  • 7
  • 17
  • 1
    I don't think there is any need to `return` the list, one can simply repeatedly call `list_expander(a)` and the list will be expanded. Also, you have a `x+=1` which does not seem to be doing anything? – mlg556 Nov 18 '19 at 19:26