Swapping Two Variables in a single line in C/C++, Java, Python, and PHP:

Earlier, we have discussed techniques to swap two integers without a temporary variable. Now we should understand how we can swap in a single line without the use of library function in python for data science.

Python:  It is very simple to perform this operation in Python, write “x,y =y,x”.

C/C++ : We can use the following in C/C++.

python for data science

Java: When it comes to Java, the sub-expression evaluations are defined clearly. According to the rules, the right-hand operand always comes after the left-hand operand in terms of evaluation.  The expression “x ^= y ^= x ^= y;” used will not produce any result as it does not comply with the Java rules. We get the result x = 0. But we can use “x = x ^ y ^ (y = x);” As already discussed evaluation is done from left to right. Consider x = 3 and y = 9 then, “x = 3 ^ 9 ^ (y = 3);”

To learn more about python for data science, you can check this and this.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.