Python 3: replacing elements that passes equality checks and calls another function to validate -
firstly, very new python. understand basics of loops used iterate through list, however, trying replace element passes basic equality check, case== " "
. when iteration reaches " "
, should replace blank spot letter "a"
, return true
.
however, not case, returns false
:( if find time point basic way this, appreciated. have searched, of answers include such things enumerate
, len
functions etc, above understanding far. thank assistance offered.
# list iterate through. mylist = ["a", "a", " ", "b", "b", "c", " ", "a", "b"] # function check conditionals def checkbook(spots,grade): if spots[0] == grade , spots[1] == grade , spots[2] == grade: return true else: return false # function iterate through mylist, calls checkbook # function return def compareelements(): elements in mylist: if elements == " ": elements = "a" print (checkbook(mylist, "a")) compareelements()
the error here:
for elements in mylist: if elements == " ": elements = "a"
in case, assigning "a"
variable elements
, , not modifying original mylist
.
in code below, mylist[i] = "a"
modify mylist
, i
index of element
, enumerate
return index , item iterate through. (changed variable name elements
element
prevent confusion)
# list iterate through. mylist = ["a", "a", " ", "b", "b", "c", " ", "a", "b"] # function check conditionals def checkbook(spots,grade): # if spots[0] == grade , spots[1] == grade , spots[2] == grade: if spots[0] == spots[1] == spots[2] == grade: # can simplified return true else: return false # function iterate through mylist, calls checkbook # function return def compareelements(): i,element in enumerate(mylist): # index, item if element == " ": mylist[i] = "a" # modifies mylist print (checkbook(mylist, "a")) compareelements() # prints true, true print(mylist) # ['a', 'a', 'a', 'b', 'b', 'c', 'a', 'a', 'b']
hope helps :)
Comments
Post a Comment