-2

For nested lists, what would the pseudocode look like so that

 mylist = [[1,2],[3,[4,5]],6]
 def mydeepcopy(mylist)
 >> [[1,2],[3,[4,5]],6] 

where it returns a completely different list through all layers

here is all I can think of

def mycopy(mylist):
    if mylist is not 1-dimensional:
        mycopy(elem for elem in mylist)
    else:
        add mylist.copy() to new list
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 3
    Nested lists are not n-dimensional arrays. – chepner Mar 12 '20 at 18:10
  • @chepner yep i didn't mean that. – Rahul Prakash Mar 12 '20 at 18:13
  • @ScottHunter I assume you would use recursion to create a copy at each level of the 1d list(s). I figured this was one of those things where it's concise but not that easy to grasp for beginners like me. – Rahul Prakash Mar 12 '20 at 18:17
  • The best way to "grasp" it is to actually try and write it, and come back if you get stuck. – Scott Hunter Mar 12 '20 at 18:19
  • @RahulPrakash Your approach would be correct. Try implementing it. – Ch3steR Mar 12 '20 at 18:20
  • What is the issue, exactly? Have you tried anything, done any research? Stack Overflow is not a free code writing service. See: [ask], [help/on-topic], https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users. – AMC Mar 12 '20 at 18:21
  • 1
    Show what you tried, we won't embarass you for it. But you won't learn if you just copy our answers. – Barmar Mar 12 '20 at 18:29
  • @barmar I just threw in my attempt. Youre right about not just copying to learn. – Rahul Prakash Mar 12 '20 at 19:01

1 Answers1

1

You have to collect the results of the recursion and return them.

def mycopy(mylist):
    newlist = []
    for element in mylist:
        if isinstance(element, list):
            newlist.append(mycopy(element))
        else:
            newlist.append(element)
    return newlist

This is overly simplified, as it only deals with lists, not tuples and dictionaries.

Note that "is not 1-dimensional" is not something you test for the entire list. It can contain a mixture of nested lists and other objects, so you need to test each element in the loop.

Barmar
  • 741,623
  • 53
  • 500
  • 612