Kodeclik Logo

Our Programs

Courses

Gifting

Learn More

Schedule

Kodeclik Blog

How to flip 1 and 0 in Python

Sometimes in a Python program, you will need to swap 0 and 1 and you would like to do it in a Python-ic way. What is a Pythonic way you ask? And when would you need to so such swaps?

For instance, in low-level programming or when working with binary data, you might need to flip specific bits. Swapping 0 and 1 is essentially flipping a single bit.

In binary image processing, swapping 0 and 1 can invert black and white pixels, creating a negative of the image.

In game logic, swapping 0 and 1 can be used to toggle states, such as turning features on or off or switching between player turns.

We will see five different ways to swap 0 and 1 in Python!

How to flip 1 and 0 in Python

Method 1: Subtraction

The simplest method to swap 0 and 1 is by subtracting the value from 1:

def swap(val):
    return 1 - val

This works because 1 - 0 = 1 and 1 - 1 = 0.

Method 2: XOR operator

The XOR (exclusive or) operation can be used to flip bits:

def swap(val):
    return val ^ 1

This method is efficient and works by flipping the least significant bit.

Method 3: Boolean Negation

By converting the value to a boolean and negating it, we can swap 0 and 1:

def swap(val):
    return int(not bool(val))

This method first converts the value to a boolean (False for 0, True for 1), negates it, and then converts it back to an integer.

Method 4: Dictionary

A dictionary can be used to create a lookup table for swapping:

swap = {0: 1, 1: 0}

def swap_value(val):
    return swap[val]

This method is clear and easily extensible if more values need to be swapped in the future.

Method 4: Lambda Function

A concise lambda function can be used to swap the values:

swap = lambda x: 1 if x == 0 else 0

This one-liner checks if the input is 0 and returns 1, otherwise it returns 0.

Understanding when and how to swap 0 and 1 is thus valuable in various programming contexts, from low-level bit manipulation to high-level application logic.

If you liked this blogpost, checkout our blogpost on how to make a number negative in Python which has similarly multiple ways to solve the same problem! Also see our blogpost on integers and their representations!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.