MGinOttawa
MGinOttawa

Reputation: 11

Create list by taking index o and repeating it based on index 1 value

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

Answers (4)

Muthuraj
Muthuraj

Reputation: 41

def createList(v,n): 
    return [v for i in range(n)]

This solution is based on list comprehension.

Upvotes: 1

MaNKuR
MaNKuR

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

Syed Ali
Syed Ali

Reputation: 219

def createList(v,n):
    print([v for i in range(n)])

You can learn function and arguments in

https://www.tutorialspoint.com/python/python_functions.htm

Upvotes: 0

cxw
cxw

Reputation: 17041

def createList(v,n):
    return [v] * n
  • You use the arguments by simply referring to them by name :) . No need to worry about which argument is first or second when you are inside 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

Related Questions