0

I currently have a function that creates a list of lists like below using 3 nested for-loops.

[[1,1,1] , [1,1,2] , .... , [3,3,3]]

However, the problem is I can't use this function if someone wants the list of list to be something like

[[1,1,1,1,1,1,1] , ..... , [9,9,9,9,9,9,9]]

which has more numbers (from 1 - 9) and more elements (7 of 1's instead of 4).

Here's my current code:

def listofList():
    temp = []
    for i in range(1,4):
        for j in range(1,4):
            for k in range(1,4):
                temp.append([i,j,k])
    return temp

Can someone provide me with a better solution? I want my function listofList() to be flexible where it could receive an input for both the size of the list of list and the elements inside the list.

cs95
  • 379,657
  • 97
  • 704
  • 746
ThomasWest
  • 485
  • 1
  • 7
  • 21
  • 2
    Don't delete your questions if you've received answers. Instead credit the answerer by voting on, and accepting their answers. Continue this behaviour and you will be banned. – cs95 Nov 07 '17 at 19:56

1 Answers1

2

Try the following:

def listofList(subLen, totalLen):
    final = [[item for i in range(subLen)] for item in range(1, totalLen+1)]
    return final

>>> listofList(9, 9)
[[1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3], [4, 4, 4, 4, 4, 4, 4, 4, 4], [5, 5, 5, 5, 5, 5, 5, 5, 5], [6, 6, 6, 6, 6, 6, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8], [9, 9, 9, 9, 9, 9, 9, 9, 9]]
>>> listofList(9, 2)
[[1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2, 2, 2]]
>>> listofList(2, 9)
[[1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8], [9, 9]]
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76