Python Forum

Full Version: help for list printing
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi
Except if i am mistaken, the function below create an empty list and append random number in this list

def toto():
    jp = []
    for i in range(4):
        jp.append(random.randint(1,10))
I try to display all the list number like this
print(*jp) but it doesn't works
Same thing if i try to print the first item
print(jp[0])
what is wrong please?
How do you try this? Your function does not return anything. I think that is the problem. Your function must return a value and then you must use this return value.
import random

def toto():
    jp = []
    for i in range(4):
        jp.append(random.randint(1,10))
    return jp

a = toto()
print(a)
print(a[0])
Output:
[1, 3, 3, 10] 1
If you are trying to print jp outside of the function (def), it won't work because jp has gone out of scope.

if you return the value, you will be able to print the values
Example:
>>> import random
>>> def toto():
...     jp = []
...     for i in range(4):
...         jp.append(random.randint(1,10))
...     return(jp)
... 
>>> jp = toto()
>>> print(*jp)
3 1 5 7
>>> print(jp[0])
3
>>>
both I and ibreeden posted at the same time.
his return is the proper way.
There is choices for this purpose in random module. So actually there is no need for repeated calls of randint.
(Apr-29-2021, 10:43 AM)ibreeden Wrote: [ -> ]How do you try this? Your function does not return anything. I think that is the problem. Your function must return a value and then you must use this return value.
import random

def toto():
    jp = []
    for i in range(4):
        jp.append(random.randint(1,10))
    return jp

a = toto()
print(a)
print(a[0])
Output:
[1, 3, 3, 10] 1

many thanks
(Apr-29-2021, 10:44 AM)Larz60+ Wrote: [ -> ]If you are trying to print jp outside of the function (def), it won't work because jp has gone out of scope.

if you return the value, you will be able to print the values
Example:
>>> import random
>>> def toto():
...     jp = []
...     for i in range(4):
...         jp.append(random.randint(1,10))
...     return(jp)
... 
>>> jp = toto()
>>> print(*jp)
3 1 5 7
>>> print(jp[0])
3
>>>

many thanks
So actually there is no need for repeated calls of randint.
@jp1 Try to remember: LEGB How Python Finds Things