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
Answer from Tim Pietzcker on Stack OverflowI 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
Just a silly way. Modifies the list instead of creating a new one.
k1.reverse()
k1[list(map(bool, k1)).index(1)] += 100
Why does [::-1] reverse a list?
python - How do I reverse a list or loop over it backwards? - Stack Overflow
loops - Traverse a list in reverse order in Python - Stack Overflow
You can use [~i] for reverse indexing rather than [-i-1]
Videos
Why would a double colon reverse a list? Is this something we just have to accept or is there some logic?
a = ['corge', 'quux', 'qux', 'baz', 'bar', 'foo'] print(a[::-1])
To get a new reversed list, apply the reversed function and collect the items into a list:
>>> xs = [0, 10, 20, 40]
>>> list(reversed(xs))
[40, 20, 10, 0]
To iterate backwards through a list:
>>> xs = [0, 10, 20, 40]
>>> for x in reversed(xs):
... print(x)
40
20
10
0
>>> xs = [0, 10, 20, 40]
>>> xs[::-1]
[40, 20, 10, 0]
Extended slice syntax is explained here. See also, documentation.
Use the built-in reversed() function:
>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
... print(i)
...
baz
bar
foo
To also access the original index, use enumerate() on your list before passing it to reversed():
>>> for i, e in reversed(list(enumerate(a))):
... print(i, e)
...
2 baz
1 bar
0 foo
Since enumerate() returns a generator and generators can't be reversed, you need to convert it to a list first.
You can do:
for item in my_list[::-1]:
print item
(Or whatever you want to do in the for loop.)
The [::-1] slice reverses the list in the for loop (but won't actually modify your list "permanently").
Friend told me this yesterday, kind of blew my mind. Had never seen this before.
from https://wiki.python.org/moin/BitwiseOperators ~ x Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1