Code to set every odd element of a to zero

python

#1

code to set every odd element of a to zero.
For example, if a were [4,10,1,7], then afterwards a would be [4,10,0,0].

any solutions to this code keeps saying unsupported operand type(s) for %: 'list' and 'int


#2

@datasurfer35592 Can you edit the question again with more clear description of the problem or include a screenshot of the code that you have.


#3

list_1=[1,2,3,4,5,6,7,8]
list_2=[]
for a in list_1:
if(a%2!=0):
ab=list_1.index(a)
list_2.append(ab)

for x in list_2:
list_1[x]=0

print(list_1)


#4

it seems to work but what is the lesson name for this exercise


#5

i do not know whats the lesson
i only solve the problem
if u wants comments on each line of code then reply me i will post


#6

That says exactly what you did wrong. You were trying to do modulus on a list. Perhaps you should have been using another name or perhaps you should have been taking out some element from the list.

The best way to set every odd element to zero is to create a new list where even numbers are added as they are and odd's are replaced by zeros. List comprehension would be the best way to write this, but you may not know the syntax of that yet, so a loop with list.append will do fine.

You can modify the elements of the list in-place, but there isn't much gain in doing so.
You should definitely not use any list methods like index like @abhishek_baliyan suggests, because that is doing a huge amount of operations (searches the list)

If you were to need the index of an element for some reason, use enumerate:

for i, num in enumerate(my_list):
    ...

#7

could you please define more for this code for i, num in enumerate(my_list):


#8

try

help(enumerate)

or google python enumerate and look for a result from python.org