current position:Home>Does Python have a, = operator?

Does Python have a, = operator?

2022-01-30 18:05:11 somenzz

Today, I'd like to share a rare knowledge point , Namely Python Is there a ,= The operator ?

Let's ignore it first , You must be quite familiar with the code related to commas :

1, Components of tuples

Parentheses without commas , Can't form tuples , Even if there is only one element , You also need commas .

In [6]: a = (1,)

In [7]: type(a)
Out[7]: tuple
 Copy code 

2、 Exchange two variables

In [8]: a = 1

In [9]: b = 2

In [10]: a, b = b, a

In [11]: f"{a = } {b = }"
Out[11]: 'a = 2 b = 1'
 Copy code 

You want to exchange three 、 four 、 Multiple , You can do the same .

3、 Disassembly list , Tuples , Or set

In [12]: a, b = [1,2]

In [13]: f"{a = } {b = }"
Out[13]: 'a = 1 b = 2'

In [14]: a, b = (3,4)

In [15]: f"{a = } {b = }"
Out[15]: 'a = 3 b = 4'

In [17]: a, b = {5,6}

In [18]: f"{a = } {b = }"
Out[18]: 'a = 5 b = 6'

In [19]:
 Copy code 

4、,= The operator ?

Understand the above operation , Now what is the result of the following code ?

a ,= [2]
b , = [2]
c , = (2,)
d , = {2}
e ,= range(2,3)
print(a,b,c,d,e)
 Copy code 

If you have results in your heart , You can see if it meets expectations :

>>> a,=[2]
>>> b , = [2]
>>> c , = (2,)
>>> d , ={2}
>>> e ,     = range(2,3)
>>> print(a,b,c,d,e)
2 2 2 2 2
>>>
 Copy code 

As long as there is only one element inside the iteratable object , You can go through ,= Take out this value in the form of , As for whether the comma and the equal sign are next to , It doesn't matter .

In a word ,,= Namely Disassembly list , Tuples , aggregate , Iteratable object The special case of , It must have only one element .

Last

Has strange knowledge increased ? If there is harvest , Please like it

copyright notice
author[somenzz],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301805092666.html

Random recommended