Python recursion append to list
I want to append to a list recursively but I cannot come up with a function that works. The function takes two arguments Show Here is my code so far:
MSeifert 138k32 gold badges318 silver badges333 bronze badges asked Feb 22, 2017 at 9:54
4 You could use a intermediate list to append to in each recursive call. That avoids these redefinition problems you're encountering currently:
When called:
answered Feb 22, 2017 at 10:06
MSeifertMSeifert 138k32 gold badges318 silver badges333 bronze badges To make your code work, you need to
On another note, you can simply replicate your list with:
Adirio 4,8801 gold badge14 silver badges25 bronze badges answered Feb 22, 2017 at 10:00
Moses KoledoyeMoses Koledoye 75.8k8 gold badges124 silver badges133 bronze badges 2 You can use
Same function can be written in a recursive way like this:
Adirio 4,8801 gold badge14 silver badges25 bronze badges answered Feb 22, 2017 at 9:58
3 Because your redefining result2 everytime. Keep result2 outside the function and it should work. Also you could consider doing data*times to replicate if data is a list or simply do
answered Feb 22, 2017 at 9:58
Abhishek JAbhishek J 2,2662 gold badges21 silver badges21 bronze badges 1 In the recursion, each time replicate_recur is called, a fresh result2 in new name space is created.
Would do what you are trying to achieve.
Rahul K P 11.9k3 gold badges34 silver badges50 bronze badges answered Feb 22, 2017 at 10:04
2 How do you add elements to a recursion list in Python?sum number in a list python using recursion. def listsum(numList):. if len(numList) == 1:. return numList[0]. return numList[0] + listsum(numList[1:]). print(listsum([1,3,5,7,9])). How do you implement a recursive function in python?Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
What is recursion example?Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself. For example, we can define the operation "find your way home" as: If you are at home, stop moving. Take one step toward home.
|