python - Replacing an even element with another element -
i having trouble part class assignment. ask replace element 0. have tried kept getting error trying divide in anyway. there way replace numbers 0, might end adding user input later on, have code finds number , replace it.
def main(): list = [7, 2, 2, 4, 5, 6, 9] print(sectionc(list)) def sectionc(list): n, in list: if list == i//2: list[n]=0 main()
the errors you're facing
your function
returns
nothing. if want result of function visible , accessible once finished, havereturn
it, otherwise function returnnone
default.while true mutable objects lists passed reference, modifying them inside function modifies them everywhere, idea explicitly
return
value.you should never name variable
list
.list()
inbuilt function in python, , declaring variable same name, lose ability call it. change variable more appropriate -collection
works, instance.n, in list
doesn't work - lists let iterate through 1 element.for in list
work,i
assigned value of element on each iteration.if want have access both index and value of element in iteration, need use
enumerate()
so:for index, item in enumerate(collection)
.enumerate()
takes list , returns list of tuples, every tuple of form(index of element, corresponding element)
in original list. used facilitate easy iteration on both index , items using syntax referenced.
the right way solve this
use list comprehension:
collection = [7, 2, 2, 4, 5, 6, 9] # renaming list variable print([x if x % 2 != 0 else 0 x in collection])
the acceptable way
this attempting do, corrected:
def sectionc(collection): index, item in enumerate(collection): # using better names n, if item % 2 == 0: # check if element collection[index] = 0 return collection
note logic here identical list comprehension. because list comprehensions expand out - benefit 1 of conciseness , readability, rather efficiency.
Comments
Post a Comment