Create a Variable Length 'Alist()'

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 into reversed(). itertools.product() also normally yields tuples instead of lists, but since we have to cast the iterator reversed() returns to a list anyway, it's no trouble. If you don't care about this, you can omit the innermost list(reversed(p)), and just leave it at p. 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() and itertools.chain(), we use the argument-unpacking operator * to pass a whole list as positional arguments. For itertools.product(), this is just duplicating the 'eligible values' range as many times as necessary, whereas for itertools.chain() it's stitching together the individual outputs of each itertools.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



Leave a reply



Submit