0

I want to run a code several times and save the result each time in the same list. I wrote a function where the output/result is an integer and every time I run it, I want this result to be in the same list. So the list will get bigger and bigger, each time I run the code/function. Do I need to use append?

martineau
  • 119,623
  • 25
  • 170
  • 301
Itay
  • 11
  • 2
  • You should add your function to the question. But yes, append would do this – Emi OB Nov 17 '21 at 15:57
  • Does this answer your question? [What is the difference between Python's list methods append and extend?](https://stackoverflow.com/questions/252703/what-is-the-difference-between-pythons-list-methods-append-and-extend) – Vens8 Nov 17 '21 at 15:58

2 Answers2

2

You can use append:

results = []
for _ in range(10):
    results.append(my_func())

or an equivalent list comprehension, e.g.:

results = [my_func() for _ in range(10)]
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • When I run the code it shows me the result in the list, but 10 times the same. And when I run the code again, it's 10 times the new result in the list – Itay Nov 17 '21 at 16:02
  • Sounds like your function returns the same thing each time you call it until you completely restart the script. Can't really help any further without knowing what the function is. If you replace `my_func()` in the above code with something like `random.randint(1, 100)` you should see that you get 10 different results, because `randint` will give you a different result each time you call it. – Samwise Nov 17 '21 at 17:22
0

well, append will be good choice to enter and it also depends on how you want the list(like if you dont want enter same value twice).

import random
def myfunc():
    rand_num = random.randint(0,100)
    return rand_num

results = []
for _ in range(10):
    results.append(myfunc())
print(results)
Yash vema
  • 1
  • 2