#13 Python Tutorial for Beginners | Swap 2 Variables in Python

 

#13 Python Tutorial for Beginners | Swap 2 Variables in Python

Welcome back aliens! My name is 720 and in this blog post, we'll see how to swap two numbers in Python. Let's say we have two variables, 'a' and 'b', with the values 5 and 6 respectively. How do we swap these two values?

Normally, in different programming languages, we have different ways of implementing this, but one thing is common in most languages - we have to use a third variable to swap them. For example, if we try to print the values of 'a' and 'b' after swapping them without using a third variable, we will see that the values are not swapped correctly.

So, the common approach is to use a temporary variable. We save the value of 'a' in the temporary variable, then assign the value of 'b' to 'a', and finally, assign the value of the temporary variable to 'b'. This way, the values are swapped correctly.

However, this approach wastes a variable. But don't worry! There is a better way to swap values without using a third variable. We can use a formula: 'a = a + b', 'b = a - b', 'a = a - b'. By using this formula, we can swap the values of 'a' and 'b' without the need for a third variable.

Another way to swap values without using a third variable is by using the XOR operation. XOR works differently and does not waste extra bits. You can search for how XOR works to understand it better.

In Python, there is a unique way to swap values. You can simply write 'a, b = b, a' to swap the values of 'a' and 'b' in one line. This is a special feature of Python.

So, there you have it! We've explored different ways to swap two numbers in Python. Feel free to ask any questions in the comment section. See you in the next blog post!

Example

# Initial values

a = 10

b = 5


# Swapping variables using a temporary variable

temp = a

a = b

b = temp


# Print the swapped values

print("a =", a)  # Output: a = 5

print("b =", b)  # Output: b = 10

# Initial values
a = 10
b = 5

# Swapping variables using tuple unpacking
a, b = b, a

# Print the swapped values
print("a =", a)  # Output: a = 5
print("b =", b)  # Output: b = 10
Both methods achieve the same result of swapping the values of a and b. You can choose the method that suits your coding style or preference.

Comments

Popular posts from this blog

#22 Python Tutorial for Beginners | Break Continue Pass in Python

Python Tutorial for Beginners

#19 Python Tutorial for Beginners | If Elif Else Statement in Python