Python List Comprehension, missing 1 required positional argument

Viewed 33

I'm making a random list generator function using a list comprehension, and keep receiving: TypeError: random_list() missing 1 required positional argument: 'length' I've noticed if I remove the length parameter the function works but I want to use the parameter. (Edit) for those who were confused, one of the comments were able to clarify what I was doing wrong, the issue wasn’t the code itself but rather how I was calling the function to test it. I’m relatively new to Python so bear with me. Thank you guys for your help.

def random_list(length, low=0, high=100):
    import random
    return [random.randint(low, high) for i in range(10)]

   
3 Answers

You seem to not give the function the length parameter it requests. If you remove the parameter, there is no missing parameter anymore.

Also, you don't use the parameter 'length' in your code. You should switch for _ in range(10): with for _ in range(length).
Also '_' is just a placeholder

Call you function like this;

random_list(10)

# to generate 10 random values...

The error happens because length is a required parameter. You can either set a default value, to make it optional or fix how you call the function.

import random

def random_list(length, low=0, high=100):
    return [random.randint(low, high) for _ in range(length)]

OR

import random

def random_list(length=10, low=0, high=100):
    return [random.randint(low, high) for _ in range(length)]
# both works:
random_list(50)
random_list() # in this case, a default 10-items list will be returned.
Related