Theo - 1 year ago 82
Python Question

# Python - Recursion: duplicate int, duplicate int in a list, duplicate int in a nested list

I'm learning recursion and I can't quite figure out why this isn't working.

What it should do:

``````>>> copy(1)
[1, 1]
>>> copy([1, 2])
[1, 1, 2, 2]
>>> copy([1, [2, 3]])
[1, 1, [2, 2, 3, 3]]
``````

So basically the code should just duplicate each integer. Note: The position in the list and the format (if it is a nested list) does not change, all this code does is insert a duplicate int beside each int in the list.

Code:

``````def copy(nested_list):
new_list = []

#if list is empty
if isinstance(nested_list, list) and len(nested_list) == 0:
return new_list

# if it's only an int
elif isinstance(nested_list, int):
new_list.append(nested_list)
new_list.append(nested_list)

else:
# if list is a list
if isinstance(nested_list, list):
for num in range(len(nested_list)):
if isinstance(nested_list[num], int):
new_list.append(nested_list[num])
new_list.append(nested_list[num])
elif isinstance(nested_list[num], list):
copy(nested_list[num])
else:
pass

return new_list
``````

It works for most of the examples, except the last one.

What it keeps giving back for the last example:

``````Expected:
[1, 1, [2, 2, 3, 3]]
Got:
[1, 1]
``````

Check this one!

``````def copy(nested_list):
new_list = []

#if list is empty
if isinstance(nested_list, list) and len(nested_list) == 0:
return new_list

# if it's only an int
elif isinstance(nested_list, int):
new_list.append(nested_list)
new_list.append(nested_list)

else:
# if list is a list
if isinstance(nested_list, list):
for num in range(len(nested_list)):
if isinstance(nested_list[num], int):
new_list.append(nested_list[num])
new_list.append(nested_list[num])
elif isinstance(nested_list[num], list):
tempList = copy(nested_list[num])
new_list.append(tempList)
else:
pass

return new_list

print(copy([1, [2, 3]]))
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download