How can I increase the length of a python list based on a parameter?

Question:

My question is related to the increase of a python list length with the use of the parameter. Specifically, I have the following lists:

l1 = list(range(10))
l2 = [False for i in range(10)]

I can merge them into a list of dictionaries by implementing the following code:

res = [{l1[i]: l2[i] for i in range(len(l1))}]

The result is the following:

[{0: False,
  1: False,
  2: False,
  3: False,
  4: False,
  5: False,
  6: False,
  7: False,
  8: False,
  9: False}]

I would like to repeat the content of the dictionary x times. For example, if x=2 the res list would be the following:

[{0: False,
  1: False,
  2: False,
  3: False,
  4: False,
  5: False,
  6: False,
  7: False,
  8: False,
  9: False},
 {0: False,
  1: False,
  2: False,
  3: False,
  4: False,
  5: False,
  6: False,
  7: False,
  8: False,
  9: False}]

My question is:
How can I repeat the content of the dictionary based on the x number and save the result on the res list?

Thanks

Asked By: Anas.S

||

Answers:

Just expand your comprehension by another loop like this:

N=3
res = [{l1[i]: l2[i] for i in range(len(l1))} for _ in range(N)]
print(res)
[{0: False,
  1: False,
  2: False,
  3: False,
  4: False,
  5: False,
  6: False,
  7: False,
  8: False,
  9: False},
 {0: False,
  1: False,
  2: False,
  3: False,
  4: False,
  5: False,
  6: False,
  7: False,
  8: False,
  9: False},
 {0: False,
  1: False,
  2: False,
  3: False,
  4: False,
  5: False,
  6: False,
  7: False,
  8: False,
  9: False}]
Answered By: Rabinzel
res = [{l1[i]: l2[i] for i in range(len(l1))}] * x
Answered By: Petr Hofman

You can multiply a list.

res = [{i: False for i in range(10)}] * x
Answered By: Caleth

You can use zip to join your 2 lists together, then repeat them with another list comprehension:

l1, l2 = [*range(10)], [False]*10
x = 3
res = [dict(zip(l1,l2)) for _ in range(x)]
Answered By: Rodrigo Rodrigues

Here is a possible solution:

result = [dict(zip(l1, l2)) for _ in range(x)]
Answered By: Riccardo Bucco
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.