How to create a list of empty lists
Question:
Apologies if this has been answered before, but I couldn’t find a similar question on here.
I am pretty new to Python and what I am trying to create is as follows:
list1 = []
list2 = []
results = [list1, list2]
This code works absolutely fine, but I was wondering if there was a quicker way to do this in one line.
I tried the following, which didn’t work, but I hope it demonstrates the sort of thing that I’m after:
result = [list1[], list2[]]
Also, in terms of complexity, would having it on one line really make any difference? Or would it be three assignments in either case?
Answers:
If you want a one-liner you can just do:
result = [[],[]]
For arbitrary length lists, you can use [ [] for _ in range(N) ]
Do not use [ [] ] * N
, as that will result in the list containing the same list object N
times
results = [[],[]]
or
results = [list(), list()]
For manually creating a specified number of lists, this would be good:
empty_list = [ [], [], ..... ]
In case, you want to generate a bigger number of lists, then putting it inside a for loop would be good:
empty_lists = [ [] for _ in range(n) ]
I would suggest using numpy because you can build higher-dimensional list of lists as well:
import numpy as np
LIST = np.zeros( [2,3] )# OR np.zeros( [2,3,6] )
It works in any number of dimensions.
Apologies if this has been answered before, but I couldn’t find a similar question on here.
I am pretty new to Python and what I am trying to create is as follows:
list1 = []
list2 = []
results = [list1, list2]
This code works absolutely fine, but I was wondering if there was a quicker way to do this in one line.
I tried the following, which didn’t work, but I hope it demonstrates the sort of thing that I’m after:
result = [list1[], list2[]]
Also, in terms of complexity, would having it on one line really make any difference? Or would it be three assignments in either case?
If you want a one-liner you can just do:
result = [[],[]]
For arbitrary length lists, you can use [ [] for _ in range(N) ]
Do not use [ [] ] * N
, as that will result in the list containing the same list object N
times
results = [[],[]]
or
results = [list(), list()]
For manually creating a specified number of lists, this would be good:
empty_list = [ [], [], ..... ]
In case, you want to generate a bigger number of lists, then putting it inside a for loop would be good:
empty_lists = [ [] for _ in range(n) ]
I would suggest using numpy because you can build higher-dimensional list of lists as well:
import numpy as np
LIST = np.zeros( [2,3] )# OR np.zeros( [2,3,6] )
It works in any number of dimensions.