Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse index in a list

For the list k1=[31.0, 72, 105.0, 581.5, 0, 0, 0], I would like to add a constant for example 100 to the first non-zero element in the reverse list. this is what I want: newk1=[0, 0, 0, 681.5, 105, 72, 31] As a beginner in Python I could not figure it out. Could you please help me. That is my code:

k1=[31.0, 72, 105.0, 581.5, 0, 0, 0]
Inverselist=[]


for i in range(len(etack1)):
    Inverselist.append(etack1[-(i+1)])
    print("Inverselist", Inverselist)
newk1=Inverselist
run_once = 0
while run_once < 1:      
    for j in  range(len(newk1)): 
        if newk1[j-1]>0: 
            newk1[j-1]=newk1[j-1]+100 
            run_once = 1 
            break
print("Newk1", newk1 )
like image 358
rezzz Avatar asked Oct 30 '17 22:10

rezzz


People also ask

How do I reverse an index list?

The best way to reverse a list using slicing in Python is to use negative indexing. This allows you to step over a list using -1, by using the code list[::-1] .

How do you reverse items in a list?

Using reversed() we can reverse the list and a list_reverseiterator object is created, from which we can create a list using list() type casting. Or, we can also use list. reverse() function to reverse list in-place.

How do you reverse index in Python?

To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0. The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward).

What is the use of reverse () method in the list?

The reverse() method reverses the sorting order of the elements.


2 Answers

I think you're overthinking this:

First, reverse the list:

inverselist = k1[::-1]

Then, replace the first nonzero element:

for i, item in enumerate(inverselist):
    if item:
        inverselist[i] += 100
        break
like image 129
Tim Pietzcker Avatar answered Oct 15 '22 22:10

Tim Pietzcker


Just a silly way. Modifies the list instead of creating a new one.

k1.reverse()
k1[list(map(bool, k1)).index(1)] += 100
like image 23
Stefan Pochmann Avatar answered Oct 15 '22 23:10

Stefan Pochmann