Home > Back-end >  Multiplying only odd indexes in a for loop
Multiplying only odd indexes in a for loop

Time:01-02

Multiplying only odd indexes with for loop Why its not working?

myList = [1, 2, 3, 4, 5]

index = 0
for num in myList:
    if index % 2 != 0:
        num *= 2
    index  = 1

print(myList) # here the output still the same list

I want the output to be [1, 4, 3, 8, 5]

CodePudding user response:

Your way isn't working because you are not assigning 'num' back into the list.

newList = [v*2 if idx % 2 != 0 else v for idx, v in enumerate(myList)]

CodePudding user response:

There are two issues in the code -

  • You need to check if the index is odd or even, and not the element.
  • Modifying num won't modify the corresponding element in the list as it does not reference the element in the list.
myList = [1, 2, 3, 4, 5]

for idx in range(len(myList)):
    if idx % 2 != 0:
        myList[idx]*=2

CodePudding user response:

Edit: I see that you have edited your question, where you fixed the first issue of checking if the items in the list are odd or not. You are however still iterating over the list using for num in myList, which under the hood creates an Iterator which moves over your list. This means that whatever you do with num, you are only modifying num and not myList[index]. In order to modify the list directly, you will need to reference myList[index]. I strongly recommend you look into using enumerate, see my original answer for how to apply it to your use-case.

Your problem is that you are checking if the value inside myList is even or odd instead of its index.

Also, modifying num within the loop does not modify the value in your original list (this can easily be noticed since in the "modified" list the odd values are not multiplied).

Using the range(len()) idiom to loop over your list would yield the following code:

myList = [1, 2, 3, 4, 5]

for idx in range(len(myList)):
    if idx % 2 != 0:
        myList[idx] *= 2

print(myList)

You could further shorten the loop/assignment by using enumerate and list comprehension:

myList = [1, 2, 3, 4, 5]

myList = [num * 2 if idx % 2 != 0 else num for idx, num in enumerate(myList)]

print(myList)

CodePudding user response:

I would use the natural list syntax L[start:stop:step]

myList = [1, 2, 3, 4, 5]

for i in mylist[1::2]:
    myList[i] = myList[i] * 2

print(myList) # [1, 4, 3, 8, 5]

  • Related