- Обмен значений двух переменных без использования третьей в Python
- Метод 1: с помощью встроенного метода
- Метод 2: с помощью побитового оператора XOR
- Метод 3: с помощью операторов сложения и вычитания
- Метод 4: с помощью операторов умножения и деления
- Метод 5: с использованием побитовых и арифметических операторов
- Заключение
- 3 Ways to Swap Variables in Python
- Swap Variables in Python without a Temporary Variable
- Swap Variables in Python with a Temporary Variable
- Swap Variables in Python Using Arithmetic
- Conclusion
- Python Swap — How to Swap Two Variables the Python Way
- Drazen Zaric
- Why does this work?
- Is this a standardized way to swap two variables in Python?
- Is there a swap function in Python?
- Blogboard.io
Обмен значений двух переменных без использования третьей в Python
В этом руководстве мы обсудим различные методы, используемые для обмена значений двух переменных (n1 и n2) без использования третьей переменной в программах Python.
P: 112 Q: 211 After swapping P and Q: P: 211 Q: 112
Метод 1: с помощью встроенного метода
Встроенный метод может работать со значениями любого типа данных, такими как string, float, it. Этот метод очень прост в использовании.
P = JavaTpoint Q = Tutorial print("Variables Value Before Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q) # Method to swap 'P' and 'Q' P, Q = Q, P print("Variables Value After Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q)
Variables Value Before Swapping: Value of P: JavaTpoint Value of Q: Tutorial Variables Value After Swapping: Value of P: Tutorial Value of Q: JavaTpoint
Метод 2: с помощью побитового оператора XOR
Метод побитового оператора XOR применяется только для целых чисел, и он работает быстрее, поскольку он использует битовую операцию, которая предназначена для того же значения result = 0 и для другого значения result = 1.
P = 5 # P = 0101 Q = 10 # Q = 1010 print("Variables Value Before Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q) # Method to swap 'P' and 'Q' P ^= Q # P = 1111, Q = 1010 Q ^= P # Q = 0101, P = 1111 P ^= Q # P = 1010, Q = 0101 print("Variables Value After Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q)
Variables Value Before Swapping: Value of P: 5 Value of Q: 10 Variables Value After Swapping: Value of P: 10 Value of Q: 5
Метод 3: с помощью операторов сложения и вычитания
Этот метод можно использовать только для числовых значений.
P = 112 Q = 211 print("Variables Value Before Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q) # Method to swap 'P' and 'Q' P = P + Q # P = 323, Q = 211 Q = P - Q # P = 323, Q = 112 P = P - Q # P = 211, Q = 112 print("Variables Value After Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q)
Variables Value Before Swapping: Value of P: 112 Value of Q: 211 Variables Value After Swapping: Value of P: 112 Value of Q: 211
Метод 4: с помощью операторов умножения и деления
Этот метод можно использовать только для числовых значений, кроме 0.
P = 11.2 Q = 21.1 print("Variables Value Before Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q) # Method to swap 'P' and 'Q' P = P * Q # P = 236.32, Q = 21.1 Q = P / Q # P = 236.32, Q = 11.2 P = P / Q # P = 21.1, Q = 11.2 print("Variables Value After Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q)
Variables Value Before Swapping: Value of P: 11.2 Value of Q: 21.1 Variables Value After Swapping: Value of P: 21.1 Value of Q: 11.2
Метод 5: с использованием побитовых и арифметических операторов
В этом методе мы будем использовать как побитовые, так и арифметические операторы. Этот метод работает только с целыми числами, но не с числами с плавающей запятой.
P = 112 Q = 211 print("Variables Value Before Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q) # Same as P = P + Q P =(P & Q) +(P | Q) ; # Same as Q = P - Q Q = P +(~Q) + 1 ; # Same as P = P - Q P = P +(~Q) + 1 ; print("Variables Value After Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q)
Variables Value Before Swapping: Value of P: 112 Value of Q: 211 Variables Value After Swapping: Value of P: 211 Value of Q: 112
Заключение
В этом руководстве мы обсудили различные методы, используемые для обмена значениями двух переменных без использования третьей.
3 Ways to Swap Variables in Python
In this tutorial, you’ll learn how to swap variables in Python, using temporary and without temporary variables. Being able to swap variables can be a useful skill to learn and has many practical applications such as in game development and web development. You’ll learn three different ways to swap variables in Python, including using temporary variables, without using temporary variables, and using arithmetic operations.
The Quick Answer: Swap Variables in Python with Tuple Unpacking
Swap Variables in Python without a Temporary Variable
The most “pythonic” way to swap variables in Python is without a temporary variable. This method is also often referred to as tuple swapping.
Before explaining how this method works, let’s take a look at what it looks like:
# Swap Variables in Python without a Temporary Variable x = 3 y = 6 x, y = y, x print('x equals: ', x) print('y equals: ', y) # Returns: # x equals: 6 # y equals: 3
We can see that this is a very easy and, importantly, readable way of swapping variables in Python. In fact, it’s likely the most Pythonic way to swap variables, given how understandable it is.
But how does this work? Is there some under the hood magic that allows us to do this? Not really. When we assign our variables to two values separated by commas, they return a tuple.
In Python, when we create an evaluative expression with the = sign, the right side of the expression is evaluated first. Because of this, when we assign something to = y, x , this is evaluated first. Behind the scenes, Python actually creates a tuple containing the two objects.
Let’s confirm this by creating the tuple and printing the type:
# Checking how tuples are created x = 3 y = 6 z = x, y print(z) print(type(z))
We can see that by separating values by a comma on the right side of the equal sign, that a tuple is created. Then, when we assign multiple values on the right, we implicitly unpack the values in the tuple.
Since the left-hand side of the expression is composed of two identifiers, the tuple is unpacked in the order that they appear in the tuple. Since the items appear in the reverse order on the right side compared to on the left side, the variables are effectively switched or swapped, implicitly. This is a highly readable method of doing things, as we’re able to understand it quite intuitively.
Now that we know this, let’s see what the operation looks like:
# Understanding variable swapping without temporary variables in Python x = 3 y = 6 x, y = y, x # Is the same as: x, y = (y, x) print('x equals: ', x) print('y equals: ', y) # Returns: # x equals: 6 # y equals: 3
We can see from the code above that our implicit tuple would return the same as an explicit tuple.
In the next section, you’ll learn how to swap variables in Python using a temporary variable.
Swap Variables in Python with a Temporary Variable
In this section, you’ll learn how to use a temporary variable. This method is equally valid, but requires the declaration of a third variable. Since the third variable isn’t used following the swapping of variables, the method explained above is preferred. That being said, it’s important to understand the different methods at your disposal.
Let’s see what this method looks like in Python:
# Swap Variables in Python with a Temporary Variable x = 3 y = 7 z = x x = y y = z print('x equals: ', x) print('y equals: ', y) # Returns: # x equals: 7 # y equals: 3
This example, while valid is a bit more confusing. We first assign the value of one variable to our third variable. Then we assign the first to the second variable, and the second to the third. (Even writing this was confusing, so I don’t blame you if you want to forget this method altogether and stick to the first method).
The reason this works is immediately understandable. However, it is difficult to understand and not the most intuitive. Because of this it can often be better simply to stick to the first method.
Swap Variables in Python Using Arithmetic
In this final section, you’ll learn a third method to swap Python variables for numeric values. We’ll be using arithmetic expressions to swap our variables – because of this it’ll only work with numerical values.
Let’s see what this approach looks like and later dive into why this approach works:
# Swap Variables with Arithmetic x = 3 y = 4 x = x + y # x = 7, y = 4 y = x - y # x = 7, y = 3 x = x - y # x = 4, y = 3 print('x equals: ', x) print('y equals: ', y) # Returns: # x equals: 4 # y equals: 3
This method works because we’re able to work with the interplay of the numbers. Again, it’s not the most practical approach, since it does require three lines where a single line would do. However, it is a good exercise to understand and to keep in your back pocket for coding interviews.
Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.
Conclusion
In this tutorial, you learned three different methods to swap variables in Python. You learned how to swap variables using a temporary variable, without a temporary variable, and with arithmetic expressions. Being able to swap variables is an important skill to learn given its many different applications in various areas.
To learn more about Python tuples, check out the official documentation here.
Python Swap — How to Swap Two Variables the Python Way
In my 10+ years in software I’ve made parts of MS Office, built data tooling and did data science for products with 100+ mil. users Here I summarize the best lessons from the industry. More posts by Drazen Zaric.
Drazen Zaric
It’s simple. For any two variables a, b , we can swap their values in a single assignment statement
In fact, it works for exchanging values of multiple variables as well
Why does this work?
This might look like a syntactic sugar for swapping variables, but in fact it’s a neat application of iterable unpacking.
Simply put: iterable unpacking happens when we assign an iterable to a list or a tuple of variables in a single assignment statement. This might sound more complicated than it actually is, so here’s an example.
Let’s say we have an array
When we do the following assignment
what we’re actually doing is equivalent to this:
Assigning values to multiple variables this way in Python is called iterable unpacking.
So how is this related to swapping variables?
When we write a, b = b, a two things happen:
- Right-hand side is evaluated first, yielding a tuple with values (, )
- This new tuple is then assigned to the left-hand side tuple a, b using iterable unpacking (note that a tuple is an iterable)
So in effect, we’re doing the following three statements, all in a single line of code:
Is this a standardized way to swap two variables in Python?
This is actually a perfectly fine, Pythonic way, to perform variable swap. As we explained, it’s not a dirty hack, but rather a special case of using iterable unpacking syntax of Python.
Is there a swap function in Python?
No, there’s no built-in function in Python that could be used to swap values of variables. But if for any reason you need one, you can simply build it using the swap syntax — a, b = b, a .
Blogboard.io
Engineering blogs by top tech companies. Search, discover, follow.