Why it outputs this? - Python 3 | Sololearn: Learn to code for FREE!

+2

Why it outputs this? - Python 3

def extend(num,list=[]): list.append(num) return (list) x = extend(1) y = extend(2) print(x,y) >>>> [1, 2] [1, 2] ⁉️

6/23/2021 9:14:48 AM

Hirani Pranav

11 Answers

New Answer

+4

default arguments in python are only evaluated once, so same default list is assigned to second argument if you didn't provide it ^^ change your function to: def extend(num,list=None): if list is None: list = [] list.append(num) return list so you will get what you're expecting ;P

+2

#___your old code...... def extend(num,list=[]): list.append(num) return (list) # here you return the entire list... a= extend(1) b= extend(2) c= extend(3) #your list exist only inside the method extend.... print ("entire list:", list) #no output #here you call the function.. but print all the return instruction... #print(a) #remove -#- to run #print(b) #remove -#- to run """________________________________________ New lines... try something like... """ #define a external/global variable... list=[] #empty list.... def exted(num): #the new function... list.append(num) print( f"added{num}" ) # x and z... they call the function exted, and Pas 4 & 7 like arguments..... x= exted(4) z= exted(7) print("new list:", list[0]) #here you print the first position on the list... lists on python starts from 0 -zero- print("list len:", len(list))

+1

I don't understand I just think that why it isn't output [1] [2]

+1

No I am not writing a code This is from challenge section where I have to answer this. But I got wrong

+1

Still doesn't explain why or what the challange is. Just use append bro

+1

Just see this https://www.sololearn.com/post/1151957/?ref=app

+1

Ya I also thought that But I am curious only why this make such a difference

+1

Slick thanks for your support

0

Single stepping through the code, the variables x and y refer to the same list. The list is also carried into the next call to extend. Also, why? You already have the append() method and use it. There seems to be no point in extend(). Especially when you can just use append() like you already did, but now you don't have to wrap it in some function that does the exact same thing.

0

Seen it, haven't you figured out that half the challenge questions are just trick questions with coding you would never actually use in real life? Plus i already told you, x and y refer to the same list

-1

Why are you using that though, append() already does what extend() is supposed to do. Plus, you gotta single step through the code. x and y are the same list