Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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))}]

My result is the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{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 I can define a way to repeat the content of the dictionary based on the x number and save the result on the res list.

Thanks

>Solution :

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

l1, l2 = [*range(10)], [False]*10
n = 3
res = [{i1:i2 for i1,i2 in zip(l1,l2)} for _ in range(n)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading