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

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -