Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement pre and post increment in Python lists?

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.

like image 518
Sriram Avatar asked Jul 24 '16 01:07

Sriram


People also ask

Why does Python have ++ --?

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.

Is there a ++ operator in Python?

Also python does come up with ++/-- operator.

Can you use ++ to increment in Python?

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.

How do you pre increment in Python?

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.


2 Answers

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.

like image 147
James Avatar answered Oct 17 '22 02:10

James


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:

  • Traverse a list in reverse order in Python
  • How to loop backwards in python?
like image 4
Josemy Avatar answered Oct 17 '22 03:10

Josemy