Reputation: 11
My apology for this most inane question. I have very basic python knowledge, and I'm working on it. I need to create a simply list in python that would take a function call with two arguments createList(v,n)
:
So that value would be a string say e
and the next argument would be a number 5
and that would then create a list-
['e','e','e','e','e','e']
Conceptually I understand that e would be at index 0
and 5
would be at index 1, but I have no idea how to actually use the arguments to make the list.
I have searched to try and learn but there is nothing so simply as this. Again, my apology for the inane question, but I am trying!
Upvotes: 0
Views: 61
Reputation: 41
def createList(v,n):
return [v for i in range(n)]
This solution is based on list comprehension.
Upvotes: 1
Reputation: 2704
Slight improved answered of @cxw. Which will work for almost all the case except when n = 0
.
def createList(v,n):
return [v] * n if (n != 0) else [v]
Since if n=0
the list [v] * 0
would become empty []
list which I think wont be expected result in your case.
Upvotes: 0
Reputation: 219
def createList(v,n):
print([v for i in range(n)])
You can learn function and arguments in
Upvotes: 0
Reputation: 17041
def createList(v,n):
return [v] * n
createList
— though they do need to be in the right order when you call createList
.[v]
makes a one-element list that contains v
.* n
, when applied to lists, expands that list to include n
copies of what it had before.return
returns the value from the function.Upvotes: 4