0
How to do this list task ?
How can I replace the even index of elements of a list by 0 ? Example L=[1,2,3,4,5,6,7,8,9] The output must be [0,1,0,3,0,5,0,7,0,9]
16 Answers
+ 2
Use list comprehension.
newArr = [0 if i%2==0 else x for x, i in enumerate(L)]
Enumerate returns tuples of (element, index) from L
Or
newArr = [0 if i%2==0 else L[i] for i in range(len(L))]
Read more:
https://www.pythonforbeginners.com/basics/list-comprehensions-in-JUMP_LINK__&&__python__&&__JUMP_LINK
https://www.w3schools.com/python/python_lists_comprehension.asp
+ 3
My way :
1- create a new arr .
2- iterate through all items in L .
3- check if "i" is even , if true push to the new arr 0 , if not push L[i]
+ 3
Iterate through list by a loop starting from 0 index , increment index value by 2 every time.
Assign L[i] =0
2 steps, try it .if not work then post your try here.
hope it helps...
+ 2
༄༂Deeproshan Kumar༂࿐ i is already the index, so list.index(list[i]) is redundant. And if an element is in the list more than once it will screw up, because it always returns the index of the first occurrence
+ 1
#memorize this example and try to find the solution by your self first, asking for ready solution will leads you to nothing!
l = [1,2,3,4,5,6,7,8,9,0]
new_list = []
for i in range(len(l)):
if l.index(l[i]) % 2 == 0:
new_list.append(0)
else:
new_list.append(i)
print(new_list)
#output
[1,0,3,0,5,0,7,0,9,0]
+ 1
Sandeep Kushwaha that gives you 0 or 1 and doesn't take the index into account
+ 1
Sandeep Kushwaha almost, but for odd indices the output has to be the element, not the index. Check the second solution from my previous answer.
Please post new suggestions in new answers, don't change the previous. This allows others to follow the conversation
+ 1
David Casson you are right. I admit that I didn't test. The error is that I confused the order in the enumeration tuples. First is the index, second the list element.
Corrected code:
L = [1,2,3,4,5,6,9,8,8,9,7,7,7,9,'a','b','c']
newArr = [0 if i%2==0 else x for i, x in enumerate(L)]
print(newArr)
newArr = [0 if i%2==0 else L[i] for i in range(len(L))]
print(newArr)
I changed the list to include some edge cases
0
Med Amine Fh you have a point but they request an unique command 😅
0
what command ?
0
Here's another option.
https://code.sololearn.com/cuJkCnbUr9T4/?ref=app
0
Benjamin Jürgens I like your solution but the two options you present produce two different results (unless I'm missing something which I may very well be). I believe your second option produces the right code. The first option seems to err in that i starts from 0 whereas x starts from 1.
https://code.sololearn.com/cc67tI3Pih6f/?ref=app
0
Add only even items to new list using modulo operator 🤣
- 1
Hi, I decided this. This code written on JS. If you use python, this code will be same.)
var L = [1,2,3,4,5,6,7,8,9];
var k = [];
for(i=0; i < L.length; i++){
if( L[i] % 2 == 0) {
} else {
k.push(0);
k.push(L[i]);
}
}
console.log(k);