The Errors You're Facing
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.
The Right Way To Solve This
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])
The Acceptable Way
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.