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.

2
  • 3
    There's no reasonable way to do this, although of course there's always hacks like defining your own integer class with a 'return the current value and then decrement' method. Commented Jul 24, 2016 at 1:34
  • Why do you want to do that? Commented Jul 24, 2016 at 2:36

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.