0

-If I have a list of length n, say:

N = [1, 3, 5, 7]  (in this case n = 4)

-I want to generate n lists out of N (so in this case, I will generate 4 lists)

-And I also want the length of these generated lists to be, say, r. (let's say r = 3 in this case):

-And all of these r values should have incrementing values of N

-so, I want something like:

[1, 1, 1]
[3. 3, 3]
[5, 5, 5]
[7, 7, 7]

-Finally, I also want to name them...so something like:

a_1 = [1, 1, 1]
a_2 = [3. 3. 3]
a_3 = [5, 5, 5]
  • 1
    What have you tried so far? – jose_bacoy Nov 11 '19 at 20:59
  • Does this answer at least the second part of your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – G. Anderson Nov 11 '19 at 21:06

1 Answers1

1

First you have to loop over your initial list, after that you can create a new list with your one value and simply multiply that by your r to get the desired output:

r = 3
N = [1, 3, 5, 7]

result = {}
for idx, item in enumerate(N):
    result[idx] = [item]*r

There are ways to create individual variables for each list but a dictionary is probably the best way to go here, I have used the index of your value in the original list as keys, output looks like this then:

{
    0: [1, 1, 1], 
    1: [3, 3, 3], 
    2: [5, 5, 5], 
    3: [7, 7, 7]
}
Max Kaha
  • 902
  • 5
  • 12
  • To change the name of the keys in dictionary, cant i put this in a loop? result['a_'+idx] = result.pop(idx1) It gives an error of converting int to str –  Nov 11 '19 at 21:33
  • You should do `result["a_%s" % idx]` instead or cast it directly to a string with `result['a_' + str(idx)]` – Max Kaha Nov 11 '19 at 21:42