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 can I duplicate all elements in an 2D array?

How can I duplicate all elements in an 2D array?
The order matters.

For example:

arr = [
  ["d", "a", "c"],
  ["b", "l", "a"],
  ["d", "u", "h"],
]

# do something

print(arr)
# Output: [
#  ["d", "d", "a", "a", "c", "c"],
#  ["b", "b", "l", "l", "a", "a"],
#  ["d", "d", "u", "u", "h", "h"],
# ]

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

>Solution :

Here is one way to do so using list comprehension:

new_arr = [[element for item in sublist for element in (item, item)] for sublist in arr]
print(new_arr)
# [['d', 'd', 'a', 'a', 'c', 'c'], ['b', 'b', 'l', 'l', 'a', 'a'], ['d', 'd', 'u', 'u', 'h', 'h']]

An alternative using for loops would be:

new_arr = []
for sublist in arr:
    new_sublist = []
    for item in sublist:
        new_sublist.extend([item, item])
    new_arr.append(new_sublist)
print(new_arr)
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