In Python how can we increment or decrement an index within the square braces of a list?
For instance, in Java the following code
array[i] = value
i--
can be written as
array[i--]
In Python, how can we implement it?
list[i--]
is not working
I am currently using
list[i] = value
i -= 1
Please suggest a concise way of implementing this step.
Because, in Python, integers are immutable (int's += actually returns a different object). Also, with ++/-- you need to worry about pre- versus post- increment/decrement, and it takes only one more keystroke to write x+=1 . In other words, it avoids potential confusion at the expense of very little gain.
Also python does come up with ++/-- operator.
If you are familiar with other programming languages, such as C++ or Javascript, you may find yourself looking for an increment operator. This operator typically is written as a++ , where the value of a is increased by 1. In Python, however, this operator doesn't exist.
Python does not have pre and post increment operators. Which will reassign b to b+1 . That is not an increment operator, because it does not increment b , it reassigns it.
Python does not have a -- or ++ command. For reasons why, see Why are there no ++ and -- operators in Python?
Your method is idiomatic Python and works fine - I see no reason to change it.
If what you need is to iterate backwards over a list, this may help you:
>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
... print i
...
baz
bar
foo
Or:
for item in my_list[::-1]:
print item
The first way is how "it should be" in Python.
For more examples:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With