Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping 1 with 0 and 0 with 1 in a Pythonic way

Tags:

python

In some part of my Python program I have a val variable that can be 1 or 0. If it's 1 I must change to 0, if it's 0 I must change to 1.

How do you do it in a Pythonic way?

if val == 1:     val = 0 elif val == 0:     val = 1 

it's too long!

I did:

swap = {0: 1, 1:0} 

So I can use it:

swap[val] 

Other ideas?

like image 873
Juanjo Conti Avatar asked Nov 22 '09 17:11

Juanjo Conti


People also ask

How do you change values in two variables?

If the two variables are numbers, their values can be swapped using arithmetic operators such as addition and subtraction ( + , - ) or multiplication and division ( * , / ). This swapping method is based on calculating the sum of the two numbers and then swapping them using the sum and the difference from the sum.

What does 0 ]* n mean in Python?

X =[0] * N , produces a list of size N, with all N elements being the value zero. for example, X = [0] * 8 , produces a list of size 8.


2 Answers

This isn't pythonic, but it is language neutral. Often val = 1 - val is simplest.

like image 86
CB Bailey Avatar answered Oct 14 '22 17:10

CB Bailey


The shortest approach is using the bitwise operator XOR.

If you want val to be reassigned:

val ^= 1 

If you do not want val to be reassigned:

val ^ 1 
like image 22
enrnpfnfp Avatar answered Oct 14 '22 15:10

enrnpfnfp