0

I have a code that goes like this:

array = [['x', 3], ['y', 3]*2]
print(array)

Output:

>> [['x', 3], ['y', 3, 'y', 3]]

However, the result that I want to get is: [['x', 3], ['y', 3], ['y', 3]]

My question is, how do you duplicate a certain element of a multi-dimensional array using operators?

Dhiraj Singh
  • 133
  • 5
Ji Hana
  • 15
  • 3
  • 2
    `array = [['x', 3], *[['y', 3]]*2]`; NB: `array[1]` and `array[2]` are same objects, mutating either of them in-place changes would be reflected in both of them. [Read about it](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Ch3steR Jun 13 '22 at 06:34
  • 2
    If you want two different objects `array = [['x', 3], *[['y', 3] for _ in range(2)]]` – Guy Jun 13 '22 at 06:37

1 Answers1

0

I don't know a way for Operators But, You can Use copy() Check the Docs

Copy the element you want then add it to the array

array = [['x', 3], ['y', 3]]
copy = array[1].copy()
array.append(copy)

You can create a new class type and customize the Operators functionality for it

Ayman
  • 363
  • 2
  • 9