Python lists, increment & return modified list -
this question has answer here:
the below code doesn't work intended:
l = [1,1] def modifylist(list): element in list: element += 1 return list
the list expect when run:
modifylist(l)
is [2,2] instead of [1,1]
can explain why python acts way?
you need access list element using index , increment:
def modifylist(lst): ind, _ in enumerate(lst): lst[ind] += 1 # access list element index , increment return lst
or use list comprehension , add 1 each element:
def modifylist(lst): lst[:] = [ele +1 ele in lst] # lst[:] changes original list return lst
if modifying original list in place, don't need return value, if want create new list return list comprehension: return [ele +1 ele in lst]
def mod_in_place(lst): lst[:] = [ele +1 ele in lst] # lst[:] changes original list
now calling function passing list change original list/object passed in:
in [3]: l = [1,1] in [4]: mod_in_place(l) in [5]: l out[5]: [2, 2]
to create new list/object:
def create_new_list(lst): return [ele + 1 ele in lst]
now create new list leaving original is:
in [7]: l = [1,1] in [8]: l2 = create_new_list(l) in [9]: l out[9]: [1, 1] # original list not changed in [10]: l2 out[10]: [2, 2]
your code creates new object element += 1
, ints immutable not affecting object stored in list. if had mutable object in list , mutated changes reflected in code create new variable temporarily , throw away.
Comments
Post a Comment