Creating lists with variable lengths Python
What do you want to fill the list with? If you just want a list with n indexes:
n = user_input_length
list = [None for x in range(n)]
Create a variable length `alist()`
OK, I'll bite. I would probably use list(bquote())
to construct a one element list containing the empty symbol, and rep
that out to the desired length.
n <- 2
rep(list(bquote()), n)
# [[1]]
#
#
# [[2]]
#
#
As a bonus, here is a collection of 5 ways to create/access the empty symbol that is needed as the content of each list element:
bquote()
#
substitute()
#
quote(expr= )
#
formals(function(x) {})$x
#
alist(,)[[1]]
#
Making a list of lists with variable size
Instead of initializing the lists with a certain number of empty sublists, you can initialize them as empty lists, and append a new empty sublist for each iteration:
lcm_list = []
prime_list = []
for i in range(len(nums)):
lcm_list.append([])
prime_list.append([])
for j in range(2, nums[i]):
...
Generating a list of dynamic length consisting of lists of dynamic lengths
You can use itertools.product()
for each subset of length, and then itertools.chain()
to concatenate the lists together.
def get_lists(a, x, y, z, m=float('-inf'), n=float('inf')):
v = list(range(x, z, y))
return list(itertools.chain(*(
(
list(reversed(p))
for p in itertools.product(*([v] * i))
if m < sum(p) < n
) for i in range(1, a + 1)
)))
This also accounts for the lower and upper bounds if you want, with optional arguments m
and n
. If not given, well, everything should fit between infinity and negative infinity.
A couple of tricks are used here.
- First of all,
itertools.product()
will display in the opposite order that you want (it varies the last element first, whereas you vary the first element first). So we feed it intoreversed()
.itertools.product()
also normally yields tuples instead of lists, but since we have to cast the iteratorreversed()
returns to a list anyway, it's no trouble. If you don't care about this, you can omit the innermostlist(reversed(p))
, and just leave it atp
. Or if you don't care about filtering the input after all, you could just remove the inner comprehension entirely. - Second, in both
itertools.product()
anditertools.chain()
, we use the argument-unpacking operator*
to pass a whole list as positional arguments. Foritertools.product()
, this is just duplicating the 'eligible values' range as many times as necessary, whereas foritertools.chain()
it's stitching together the individual outputs of eachitertools.product()
. This idiom is required for a lot of itertools abuse.
Otherwise this is just a few nested comprehensions. Technically you could do it in a one-liner, but I find that putting v
in a variable and doing [v] * i
is nicer than doing (range(x, z, y) for _ in range(i))
.
Related Topics
Left_Join Two Data Frames and Overwrite
S4 Classes: Multiple Types Per Slot
How to Add a Non-Overlapping Legend to Associate Colors with Categories in Pairs()
Conditionally Apply Pipeline Step Depending on External Value
Rank Per Row Over Multiple Columns in R
Questions About Set.Seed() in R
Constrain Multiple Sliderinput in Shiny to Sum to 100
Can Ggplot Make 2D Summaries of Data
Easiest Way to Discretize Continuous Scales for Ggplot2 Color Scales
Include Zero Frequencies in Frequency Table for Likert Data
Dplyr Filter() with SQL-Like %Wildcard%
How to Remove Specific Special Characters in R
Igraph Axes Xlim Ylim Plot Incorrectly
How Calculate Growth Rate in Long Format Data Frame
Importing Wikipedia Tables in R
Shiny R - Download the Result of a Table
How to Pass the "..." Parameters in the Parent Function to Its Two Children Functions in R