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 copy the elements of the list within the list?

I have a list list_1 = [[1,2,3], [4,5,6], [7,8,9], ....]. I want [[1,2,3], [1,2,3], [4,5,6], [4,5,6], [7,8,9], [7,8,9]]. How can i achieve this?
Its like basically copying each element of the list to its consecutive index.

>Solution :

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

from copy import deepcopy

def multiply_list_elem(lst, n):
    out = list()
    for elem in lst:
        for _ in range(n):
            out.append(deepcopy(elem))
    return out

if __name__ == '__main__':
    list_1 = [[1,2,3], [4,5,6], [7,8,9]]
    print(multiply_list_elem(list_1, 2))
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