While using recursion, list won't add any new elements
I am asked to define a function that takes in a list and returns another list, all that while using recursion. However when I run the else command and I print the lst_
, the output shows that on every run the list contains a single element, instead of having the doubles added one by one.Also I try not to use append()
Thoughts?
def double(lst, lst_ = ):
"""
parameters : lst of type list;
returns : another list with lst's elements doubled
"""
if len(lst) == 0:
return lst_
else:
lst[0] = int(lst[0]) + int(lst[0])
lst_ = lst_ + lst[0:1]
print(lst_)
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
This is the output
[2]
[4]
[6]
[8]
[10]
[12]
[14]
[16]
python list recursion
add a comment |
I am asked to define a function that takes in a list and returns another list, all that while using recursion. However when I run the else command and I print the lst_
, the output shows that on every run the list contains a single element, instead of having the doubles added one by one.Also I try not to use append()
Thoughts?
def double(lst, lst_ = ):
"""
parameters : lst of type list;
returns : another list with lst's elements doubled
"""
if len(lst) == 0:
return lst_
else:
lst[0] = int(lst[0]) + int(lst[0])
lst_ = lst_ + lst[0:1]
print(lst_)
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
This is the output
[2]
[4]
[6]
[8]
[10]
[12]
[14]
[16]
python list recursion
Write exactly what you need. With output and input data.
– Rudolf Morkovskyi
Nov 11 at 11:32
@RudolfMorkovskyi edited
– user10158754
Nov 11 at 11:38
add a comment |
I am asked to define a function that takes in a list and returns another list, all that while using recursion. However when I run the else command and I print the lst_
, the output shows that on every run the list contains a single element, instead of having the doubles added one by one.Also I try not to use append()
Thoughts?
def double(lst, lst_ = ):
"""
parameters : lst of type list;
returns : another list with lst's elements doubled
"""
if len(lst) == 0:
return lst_
else:
lst[0] = int(lst[0]) + int(lst[0])
lst_ = lst_ + lst[0:1]
print(lst_)
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
This is the output
[2]
[4]
[6]
[8]
[10]
[12]
[14]
[16]
python list recursion
I am asked to define a function that takes in a list and returns another list, all that while using recursion. However when I run the else command and I print the lst_
, the output shows that on every run the list contains a single element, instead of having the doubles added one by one.Also I try not to use append()
Thoughts?
def double(lst, lst_ = ):
"""
parameters : lst of type list;
returns : another list with lst's elements doubled
"""
if len(lst) == 0:
return lst_
else:
lst[0] = int(lst[0]) + int(lst[0])
lst_ = lst_ + lst[0:1]
print(lst_)
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
This is the output
[2]
[4]
[6]
[8]
[10]
[12]
[14]
[16]
python list recursion
python list recursion
edited Nov 11 at 11:37
asked Nov 11 at 11:26
user10158754
Write exactly what you need. With output and input data.
– Rudolf Morkovskyi
Nov 11 at 11:32
@RudolfMorkovskyi edited
– user10158754
Nov 11 at 11:38
add a comment |
Write exactly what you need. With output and input data.
– Rudolf Morkovskyi
Nov 11 at 11:32
@RudolfMorkovskyi edited
– user10158754
Nov 11 at 11:38
Write exactly what you need. With output and input data.
– Rudolf Morkovskyi
Nov 11 at 11:32
Write exactly what you need. With output and input data.
– Rudolf Morkovskyi
Nov 11 at 11:32
@RudolfMorkovskyi edited
– user10158754
Nov 11 at 11:38
@RudolfMorkovskyi edited
– user10158754
Nov 11 at 11:38
add a comment |
4 Answers
4
active
oldest
votes
If the idea is to return a copy without modifying the original, I would not recommend using the mutable default argument.
Instead,
def double(lst):
if not lst:
return
return [2*lst[0], *double(lst[1:])] # [2*lst[0]] + double(lst[1:])
The recursive case must return a fresh list, and the base case will check for, and return an empty list.
lst1 = double([1,2,3,4,5,6,7,8])
print(lst1)
[2, 4, 6, 8, 10, 12, 14, 16]
If you want to have a little fun, you can attempt a generator-based recursive solution using yield from
(generator delegation):
def double(lst):
if lst:
yield 2*lst[0]
yield from double(lst[1:])
lst = list(double([1,2,3,4,5,6,7,8]) )
print(lst)
[2, 4, 6, 8, 10, 12, 14, 16]
add a comment |
Use .append()
on list to add elements at the end:
def double(lst, lst_ = ):
"""
parameters : lst of type list;
returns : another list with lst's elements doubled
"""
if len(lst) == 0:
return lst_
else:
lst[0] += lst[0]
lst_.append(lst[0])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
# [2, 4, 6, 8, 10, 12, 14, 16]
Also, note that this line lst[0] = int(lst[0]) + int(lst[0])
in you code can be shortened to lst[0] += lst[0]
, because you are dealing with integers only and that explicit casting is redundant.
add a comment |
If you don't want to use append(). Then you can use this solution:
def double(lst, lst_ = ):
if not lst:
return lst_
else:
return [lst[0] * 2 , *double(lst[1:])]
print(double([1,2,3,4,5,6,7,8]))
The output will be : [2, 4, 6, 8, 10, 12, 14, 16]
Just in case you are wondering with the *double(lst[1:]) call: * is used for unpacking argument list. Read more here.
If you call without the * you will get an output like:
[2, [4, [6, [8, [10, [12, [14, [16, ]]]]]]]]
Another easy solution will be:
def double(lst, lst_ = ):
if not lst:
return lst_
else:
lst[0] = lst[0] * 2
lst_ = lst_.append(lst[0])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
add a comment |
Try this way:
def double(lst, lst_ = ):
if len(lst) == 0:
return lst_
else:
lst[0] = int(lst[0]) + int(lst[0])
lst_.extend(lst[:1])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
#=> [2, 4, 6, 8, 10, 12, 14, 16]
Would it be possible to do this without usingappend()
?
– user10158754
Nov 11 at 11:34
Thisfor item in lst[0:1]:
is unnecessary. You can directly add to list.
– Austin
Nov 11 at 11:35
@Austin Yup, thanks.
– iGian
Nov 11 at 12:40
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248247%2fwhile-using-recursion-list-wont-add-any-new-elements%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
If the idea is to return a copy without modifying the original, I would not recommend using the mutable default argument.
Instead,
def double(lst):
if not lst:
return
return [2*lst[0], *double(lst[1:])] # [2*lst[0]] + double(lst[1:])
The recursive case must return a fresh list, and the base case will check for, and return an empty list.
lst1 = double([1,2,3,4,5,6,7,8])
print(lst1)
[2, 4, 6, 8, 10, 12, 14, 16]
If you want to have a little fun, you can attempt a generator-based recursive solution using yield from
(generator delegation):
def double(lst):
if lst:
yield 2*lst[0]
yield from double(lst[1:])
lst = list(double([1,2,3,4,5,6,7,8]) )
print(lst)
[2, 4, 6, 8, 10, 12, 14, 16]
add a comment |
If the idea is to return a copy without modifying the original, I would not recommend using the mutable default argument.
Instead,
def double(lst):
if not lst:
return
return [2*lst[0], *double(lst[1:])] # [2*lst[0]] + double(lst[1:])
The recursive case must return a fresh list, and the base case will check for, and return an empty list.
lst1 = double([1,2,3,4,5,6,7,8])
print(lst1)
[2, 4, 6, 8, 10, 12, 14, 16]
If you want to have a little fun, you can attempt a generator-based recursive solution using yield from
(generator delegation):
def double(lst):
if lst:
yield 2*lst[0]
yield from double(lst[1:])
lst = list(double([1,2,3,4,5,6,7,8]) )
print(lst)
[2, 4, 6, 8, 10, 12, 14, 16]
add a comment |
If the idea is to return a copy without modifying the original, I would not recommend using the mutable default argument.
Instead,
def double(lst):
if not lst:
return
return [2*lst[0], *double(lst[1:])] # [2*lst[0]] + double(lst[1:])
The recursive case must return a fresh list, and the base case will check for, and return an empty list.
lst1 = double([1,2,3,4,5,6,7,8])
print(lst1)
[2, 4, 6, 8, 10, 12, 14, 16]
If you want to have a little fun, you can attempt a generator-based recursive solution using yield from
(generator delegation):
def double(lst):
if lst:
yield 2*lst[0]
yield from double(lst[1:])
lst = list(double([1,2,3,4,5,6,7,8]) )
print(lst)
[2, 4, 6, 8, 10, 12, 14, 16]
If the idea is to return a copy without modifying the original, I would not recommend using the mutable default argument.
Instead,
def double(lst):
if not lst:
return
return [2*lst[0], *double(lst[1:])] # [2*lst[0]] + double(lst[1:])
The recursive case must return a fresh list, and the base case will check for, and return an empty list.
lst1 = double([1,2,3,4,5,6,7,8])
print(lst1)
[2, 4, 6, 8, 10, 12, 14, 16]
If you want to have a little fun, you can attempt a generator-based recursive solution using yield from
(generator delegation):
def double(lst):
if lst:
yield 2*lst[0]
yield from double(lst[1:])
lst = list(double([1,2,3,4,5,6,7,8]) )
print(lst)
[2, 4, 6, 8, 10, 12, 14, 16]
edited Nov 11 at 11:42
answered Nov 11 at 11:36
coldspeed
118k18109185
118k18109185
add a comment |
add a comment |
Use .append()
on list to add elements at the end:
def double(lst, lst_ = ):
"""
parameters : lst of type list;
returns : another list with lst's elements doubled
"""
if len(lst) == 0:
return lst_
else:
lst[0] += lst[0]
lst_.append(lst[0])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
# [2, 4, 6, 8, 10, 12, 14, 16]
Also, note that this line lst[0] = int(lst[0]) + int(lst[0])
in you code can be shortened to lst[0] += lst[0]
, because you are dealing with integers only and that explicit casting is redundant.
add a comment |
Use .append()
on list to add elements at the end:
def double(lst, lst_ = ):
"""
parameters : lst of type list;
returns : another list with lst's elements doubled
"""
if len(lst) == 0:
return lst_
else:
lst[0] += lst[0]
lst_.append(lst[0])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
# [2, 4, 6, 8, 10, 12, 14, 16]
Also, note that this line lst[0] = int(lst[0]) + int(lst[0])
in you code can be shortened to lst[0] += lst[0]
, because you are dealing with integers only and that explicit casting is redundant.
add a comment |
Use .append()
on list to add elements at the end:
def double(lst, lst_ = ):
"""
parameters : lst of type list;
returns : another list with lst's elements doubled
"""
if len(lst) == 0:
return lst_
else:
lst[0] += lst[0]
lst_.append(lst[0])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
# [2, 4, 6, 8, 10, 12, 14, 16]
Also, note that this line lst[0] = int(lst[0]) + int(lst[0])
in you code can be shortened to lst[0] += lst[0]
, because you are dealing with integers only and that explicit casting is redundant.
Use .append()
on list to add elements at the end:
def double(lst, lst_ = ):
"""
parameters : lst of type list;
returns : another list with lst's elements doubled
"""
if len(lst) == 0:
return lst_
else:
lst[0] += lst[0]
lst_.append(lst[0])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
# [2, 4, 6, 8, 10, 12, 14, 16]
Also, note that this line lst[0] = int(lst[0]) + int(lst[0])
in you code can be shortened to lst[0] += lst[0]
, because you are dealing with integers only and that explicit casting is redundant.
edited Nov 11 at 11:38
answered Nov 11 at 11:33
Austin
9,3273828
9,3273828
add a comment |
add a comment |
If you don't want to use append(). Then you can use this solution:
def double(lst, lst_ = ):
if not lst:
return lst_
else:
return [lst[0] * 2 , *double(lst[1:])]
print(double([1,2,3,4,5,6,7,8]))
The output will be : [2, 4, 6, 8, 10, 12, 14, 16]
Just in case you are wondering with the *double(lst[1:]) call: * is used for unpacking argument list. Read more here.
If you call without the * you will get an output like:
[2, [4, [6, [8, [10, [12, [14, [16, ]]]]]]]]
Another easy solution will be:
def double(lst, lst_ = ):
if not lst:
return lst_
else:
lst[0] = lst[0] * 2
lst_ = lst_.append(lst[0])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
add a comment |
If you don't want to use append(). Then you can use this solution:
def double(lst, lst_ = ):
if not lst:
return lst_
else:
return [lst[0] * 2 , *double(lst[1:])]
print(double([1,2,3,4,5,6,7,8]))
The output will be : [2, 4, 6, 8, 10, 12, 14, 16]
Just in case you are wondering with the *double(lst[1:]) call: * is used for unpacking argument list. Read more here.
If you call without the * you will get an output like:
[2, [4, [6, [8, [10, [12, [14, [16, ]]]]]]]]
Another easy solution will be:
def double(lst, lst_ = ):
if not lst:
return lst_
else:
lst[0] = lst[0] * 2
lst_ = lst_.append(lst[0])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
add a comment |
If you don't want to use append(). Then you can use this solution:
def double(lst, lst_ = ):
if not lst:
return lst_
else:
return [lst[0] * 2 , *double(lst[1:])]
print(double([1,2,3,4,5,6,7,8]))
The output will be : [2, 4, 6, 8, 10, 12, 14, 16]
Just in case you are wondering with the *double(lst[1:]) call: * is used for unpacking argument list. Read more here.
If you call without the * you will get an output like:
[2, [4, [6, [8, [10, [12, [14, [16, ]]]]]]]]
Another easy solution will be:
def double(lst, lst_ = ):
if not lst:
return lst_
else:
lst[0] = lst[0] * 2
lst_ = lst_.append(lst[0])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
If you don't want to use append(). Then you can use this solution:
def double(lst, lst_ = ):
if not lst:
return lst_
else:
return [lst[0] * 2 , *double(lst[1:])]
print(double([1,2,3,4,5,6,7,8]))
The output will be : [2, 4, 6, 8, 10, 12, 14, 16]
Just in case you are wondering with the *double(lst[1:]) call: * is used for unpacking argument list. Read more here.
If you call without the * you will get an output like:
[2, [4, [6, [8, [10, [12, [14, [16, ]]]]]]]]
Another easy solution will be:
def double(lst, lst_ = ):
if not lst:
return lst_
else:
lst[0] = lst[0] * 2
lst_ = lst_.append(lst[0])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
answered Nov 11 at 12:10
Anurag
80111
80111
add a comment |
add a comment |
Try this way:
def double(lst, lst_ = ):
if len(lst) == 0:
return lst_
else:
lst[0] = int(lst[0]) + int(lst[0])
lst_.extend(lst[:1])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
#=> [2, 4, 6, 8, 10, 12, 14, 16]
Would it be possible to do this without usingappend()
?
– user10158754
Nov 11 at 11:34
Thisfor item in lst[0:1]:
is unnecessary. You can directly add to list.
– Austin
Nov 11 at 11:35
@Austin Yup, thanks.
– iGian
Nov 11 at 12:40
add a comment |
Try this way:
def double(lst, lst_ = ):
if len(lst) == 0:
return lst_
else:
lst[0] = int(lst[0]) + int(lst[0])
lst_.extend(lst[:1])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
#=> [2, 4, 6, 8, 10, 12, 14, 16]
Would it be possible to do this without usingappend()
?
– user10158754
Nov 11 at 11:34
Thisfor item in lst[0:1]:
is unnecessary. You can directly add to list.
– Austin
Nov 11 at 11:35
@Austin Yup, thanks.
– iGian
Nov 11 at 12:40
add a comment |
Try this way:
def double(lst, lst_ = ):
if len(lst) == 0:
return lst_
else:
lst[0] = int(lst[0]) + int(lst[0])
lst_.extend(lst[:1])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
#=> [2, 4, 6, 8, 10, 12, 14, 16]
Try this way:
def double(lst, lst_ = ):
if len(lst) == 0:
return lst_
else:
lst[0] = int(lst[0]) + int(lst[0])
lst_.extend(lst[:1])
return double(lst[1:])
print(double([1,2,3,4,5,6,7,8]))
#=> [2, 4, 6, 8, 10, 12, 14, 16]
edited Nov 11 at 12:40
answered Nov 11 at 11:33
iGian
3,0452622
3,0452622
Would it be possible to do this without usingappend()
?
– user10158754
Nov 11 at 11:34
Thisfor item in lst[0:1]:
is unnecessary. You can directly add to list.
– Austin
Nov 11 at 11:35
@Austin Yup, thanks.
– iGian
Nov 11 at 12:40
add a comment |
Would it be possible to do this without usingappend()
?
– user10158754
Nov 11 at 11:34
Thisfor item in lst[0:1]:
is unnecessary. You can directly add to list.
– Austin
Nov 11 at 11:35
@Austin Yup, thanks.
– iGian
Nov 11 at 12:40
Would it be possible to do this without using
append()
?– user10158754
Nov 11 at 11:34
Would it be possible to do this without using
append()
?– user10158754
Nov 11 at 11:34
This
for item in lst[0:1]:
is unnecessary. You can directly add to list.– Austin
Nov 11 at 11:35
This
for item in lst[0:1]:
is unnecessary. You can directly add to list.– Austin
Nov 11 at 11:35
@Austin Yup, thanks.
– iGian
Nov 11 at 12:40
@Austin Yup, thanks.
– iGian
Nov 11 at 12:40
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248247%2fwhile-using-recursion-list-wont-add-any-new-elements%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Write exactly what you need. With output and input data.
– Rudolf Morkovskyi
Nov 11 at 11:32
@RudolfMorkovskyi edited
– user10158754
Nov 11 at 11:38