You can assign your variable to None:
>>> a = range(20)
>>> a[15:None:-1]
[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>>
Answer from zhangyangyu on Stack OverflowFriend 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
Videos
Is Enumerate Memory Efficient?
Is Enumerate Zero-Based or One-Based?
What are the Related Courses and Blogs Provided by The Knowledge Academy?
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
Just a silly way. Modifies the list instead of creating a new one.
k1.reverse()
k1[list(map(bool, k1)).index(1)] += 100
If I understood your question properly then I think you're looking for enumerate():
>>> for ind, char in enumerate("mystring"):
... print ind,char
...
0 m
1 y
2 s
3 t
4 r
5 i
6 n
7 g
help on enumerate:
>>> enumerate?
Docstring:
enumerate(iterable[, start]) -> iterator for index, value of iterable
Return an enumerate object. iterable must be another object that supports
iteration. The enumerate object yields pairs containing a count (from
start, which defaults to zero) and a value yielded by the iterable argument.
enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), ...
Edit:
To get the index of first match of any substring you can use str.index or str.find.
str.index will raise ValueError if the item is not found and str.find will return -1:
>>> strs = "hello"
>>> strs.index("h")
0
>>> strs.find("h")
0
>>> strs.find("m")
-1
>>> strs.index("m")
Traceback (most recent call last):
File "<ipython-input-9-5f19ab4b0632>", line 1, in <module>
strs.index("m")
ValueError: substring not found
You are probably looking for the index method:
>>> s = 'hello'
>>> s.index('h')
0