I am having trouble with this part with my class assignment. It ask to replace an even element with a 0. I have tried but kept getting error for trying to divide it in anyway. Is there a way to replace even numbers with 0, I might end up adding a user input later on, so have to code where it finds an even number and replace it.
def main():
list = [7, 2, 2, 4, 5, 6, 9]
print(sectionC(list))
def sectionC(list):
for n, i in list:
if list == i//2:
list[n]=0
main()
Your function returns
nothing. If you want the result of the function to be visible and accessible once finished, you have to return
it, otherwise your function will return None
by default.
While it is true that mutable objects like lists are passed
effectively by reference, so that modifying them inside your function
modifies them everywhere, it is always a good idea to explicitly return
a value.
You should never name a variable list
. list()
is an inbuilt function in Python, and by declaring a variable with the same name, you lose the ability to call it. Change your variable to something more appropriate - collection
works, for instance.
n, i in list
doesn't work - lists only let you iterate through one element. So for i in list
will work, where i
is assigned the value of an element on each iteration.
If you want to have access to both the index and the value of an element in iteration, you need to use enumerate()
like so: for index, item in enumerate(collection)
.
enumerate()
takes a list and returns a list of tuples, where every tuple is of the form (index of element, corresponding element)
in the original list. It is used primarily to facilitate easy iteration over both index and items using the syntax I just referenced.
Use a list comprehension:
collection = [7, 2, 2, 4, 5, 6, 9] # renaming list variable
print([x if x % 2 != 0 else 0 for x in collection])
This is what you were attempting to do, corrected:
def sectionC(collection):
for index, item in enumerate(collection): # using better names than n, i
if item % 2 == 0: # check if element is even
collection[index] = 0
return collection
Note that the logic here is identical to the list comprehension. This is because list comprehensions actually expand out to something exactly like this - the benefit is one of conciseness and readability, rather than efficiency.