Wednesday, January 6, 2016

A python list interview question



interview preparation questions:::

def extendlist(val,list=[]):
list.append(val)
return list
list1 = extendlist(10)
list2 = extendlist(123,[])
list3 = extendlist('a')
print "list1 = %s" % list1
print 'list2 = %s" % list2
print "list3 = %s' % lsit3


hint prepared by myself::;
%s means a place holder that formats values into strings; for example::
name =raw_input("who are you?")
print " hello %s" % (name)
here %s tokens allows to insert and ( potentially format) a string.Notice that the %s token is replace by whatever i pass to the string after % symbol.
"Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike".
 for integer %d is used instead of %s.


the output fort this question is
list1 = [10,'a']
list2 = [123]
list3 = [10,'a']
the output may not be the one we used to get on regular way but it is quite different because the argument is not set to default value of [] each time extendlist is called
however what actually happens is that the new default list is created
only once when the function is defined and the that same list is then  then used subsquently whenever extendlist is invoked without a list argument being specified. This is because expressions in default arguments are calculated when the functions is defined ,not when it's called.
source:http://www.toptal.com/python/interview-questions

1 comment: