How to Construct a List of Lists in Python
To create a list of lists in Python, append them to a list like this:
list_1 = [1,2,3]
list_2 = [4,5,6]
list_3 = [7,8,9]
lists = []
lists.append(list_1)
lists.append(list_2)
lists.append(list_3)
print(lists)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
.append()
only takes one argument so you will have to append each one manually.
With list Comprehension
Another way to achieve the same result with a cleaner syntax is to use Python list comprehension. Let's say we want to combine three lists into one list we could loop through them and append each one like this:
list_1 = [1,2,3]
list_2 = [4,5,6]
list_3 = [7,8,9]
items = {1: list_1, 2: list_2, 3: list_3}
lists = [items[i] for i in items]
print(lists)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]