6

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.

Sriram
  • 999
  • 2
  • 12
  • 29

2 Answers2

7

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.

Community
  • 1
  • 1
James
  • 2,843
  • 1
  • 14
  • 24
4

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:

Community
  • 1
  • 1
Josemy
  • 810
  • 1
  • 12
  • 29