python - Writing a Function that Creates and Returns a List -


i trying write function creates , returns list of specified length, containing repetitions of specified value. i'm unsure of how function create list arguments inputted. appreciated! i'm not asking code written me, simple explanation of python functions should using or point me in right direction. code have far this, know wrong:

def makelist(a,b):     mylist = []     mylist = makelist     return mylist 

edit:

since said wanted use loop:

>>> def makelist(a, b): ...     mylist = [] ...     _ in range(b): ...         mylist.append(a) ...     return mylist ... >>> makelist('a', 12) ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'] >>> makelist(3, 12) [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] >>> 


actually, because solution quite short, easiest way explain demonstration:

>>> def makelist(a, b): ...     return [a] * b ... >>> makelist('a', 12) ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'] >>> makelist(3, 12) [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] >>> 

basically, place a in list , multiply list b. doing create list contents a repeated b times.

it should noted that, if a mutable object (such list), above function return list contains b references same object a.

if behavior undesirable, can use list comprehension , copy.deepcopy:

>>> copy import deepcopy >>> def makelist(a, b): ...     return [deepcopy(a) _ in range(b)] ... >>> makelist('a', 12) ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'] >>> makelist(3, 12) [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] >>> 

finally, here useful references regarding tools used here:

  1. copy.deepcopy

  2. sequence types

  3. range

  4. list comprehensions


note: in of demonstrations, assumed b integer.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -