Python: How to Swap Variable values without Intermediary

In Python, you can swap values without defining the intermediary variables. This is possible with a tuple. I have shared a good example of how to do this.

Python: How to Swap Variables with Tuple

How to Swap Variable in Python.

You can swap values for two variables using a tuple. The prime purpose of a tuple is you can hold multiple values. In this example, those are a and b. Here the tuple accepts two values. When you supply those, it swaps values and gives an output when you print them.


def swap(a, b): 
return b,a 


Example-1 to call the tuple.

i = "Hello world"
j = "This is ApplyBigAnalytics" 
i, j = swap(i, j) 
print(i) 
print(j) 


Example-2 to call the tuple.

i = 1 
j = 2 
i, j = swap(i,j) 
print(i) 
print(j)


The Result is:

This is ApplyBigAnalytics 
Hello world 

Comments

Popular posts from this blog

Hyperledger Fabric: 20 Real Interview Questions

How to Fix Python Syntax Errors Quickly

7 AWS Interview Questions asked in Infosys, TCS