-4

Is there some way to create a list of lists in Python? Analogous to zeroes or similar functions.

What I am thinking of is something like this (pseudocode to follow):

def listoflists(nlists, nitems, fill)
    ...

listoflists(2,3, -1) # returns [[-1,-1,-1],[-1,-1,-1]]
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Does this answer your question? [Python: list of lists](https://stackoverflow.com/questions/11487049/python-list-of-lists) – Mark Snyder Feb 13 '20 at 00:54
  • Have you done any research? Also, variable and function names should follow the `lower_case_with_underscores` style. – AMC Feb 13 '20 at 01:18

4 Answers4

2

Not sure if there's a library function to do it, but here's how I would do it:

def listoflists(nList, nItem, fill): return [[fill for _ in range(nItem)] for _ in range(nList)]

This uses list comprehension to make a list of size nItem nList times.

Misha Melnyk
  • 409
  • 2
  • 5
  • 1
    Using the same variable name for both loops is a bad habit, to say the least. By convention, variables named `_` are unused, which is what you should do here. – AMC Feb 13 '20 at 01:21
1

You can create a list

root_list = []

and just append your sublists

root_list.append([1, 1, 1])

Benjamin Basmaci
  • 2,247
  • 2
  • 25
  • 46
0

just need to do this:

def list_of_list(n_list, n_elements, fill):
  x = [fill] * n_elements
  y = [x] * n_list
  return y

print(list_of_list(2, 3, -1))

Bye.

0

This should work, thanks!

def listoflists(nlists, nitems, fill):
    f_list = []
    for i in range(nlists):
        n_list = []
        for j in range(nitems):
            n_list.append(fill)
        f_list.append(n_list)
        n_list = []
    return f_list

print(listoflists(2,3,-1))