3

I'm trying to create a function with three parameters: x,y,val that will return a two dimensional array with x rows and y columns and every single value initialized to val. e.g.

myList = createList(2,3,"-")

would create the resulting list: [["-", "-", "-"] ["-", "-", "-"]]

so far I've created the following function for this but it puts all the initial values on one list:

def createList(x,y,val):
    myList=[]
    for i in range(x):
        for j in range(y):
            myList.append(val)
    return myList

print(createList(2,3,"-"))

which creates the output: ['-', '-', '-', '-', '-', '-']

  • thanks for this, I've updated my original post now :) – Stuart Forsyth Nov 13 '17 at 05:07
  • this is not a duplicate because the other post you refer to did not accept a parameter for the value to use for initialising the list, although I accept that the post is useful and could probably have been adapted to solve my problem. Still new here and learning my way around! – Stuart Forsyth Nov 13 '17 at 05:24
  • I assumed from the code you posted that you understand how to pass args to a function and how to use those args inside the function, and thus that your primary question was about the actual 2D list construction, which is why I considered that the question I linked has all the info you need to solve your problem. – PM 2Ring Nov 13 '17 at 05:28
  • BTW, there's nothing wrong with asking duplicate questions, although you are expected to make a search first to see if you can use the info in existing answers to solve your current problem. The reason that we close questions as duplicates is not because such questions are intrinsically bad (they aren't), it's to try to pool the answers together so that they can easily be compared and voted on. – PM 2Ring Nov 13 '17 at 05:32

2 Answers2

2

You could simply use the list comprehension in python to create a 2D array in python.

def create2DArray(x, y, val):
    return [[val for i in range(y)] for j in range(x)]

myList = create2DArray(2, 3, '-')
print(myList)
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
Himanshu Bansal
  • 475
  • 4
  • 19
0

You could use a list comprehension to do this. First, create a list of x lists:

[[] for i in range(x)]

You can also create a list of y val:

[val for j in range(y)]

Combining these would give you:

createList(x,y,val):
    return [["-" for j in range(y)] for i in range(x)]
serena7889
  • 36
  • 3