There are 6 types of replication syntax in Python
Basic Form
' spam '
Tuple Assignment
' spam ' ' Ham '
List Assignmen
>>>[spam, ham] = ['spam'ham']
Sequence Assignment
' spam '
Extended sequence Unpacking (Python 3.X)
>>>a, *b ='spam'>>>a's'>>>b#b The result of the assignment is a list['P','a','m']>>>a, *b, C ='spam'>>>a's'>>>b['P','a']>>>C'm'
There are five points to note about this type of replication:
1 for an assignment result with an * number variable, always a list, even if only one element is included
2 If no remaining value is assigned to a variable with an * number, it is an empty list
>>>>a, B, C, *e, d = " spam Span style= "COLOR: #800000" > " >>>a " s " >>>b " p " >>>c " a " >>>d " m " >>>e # Independent of the position of the * variable []
3 error if 2 or more than 2 * variables appear in an assignment statement
4 The number of variables and the number of values do not match, will also error
' spam ' # The number of values is too low Not enough values to unpack (expected 5, got 4)'spam' #
variable number is too small valueerror:too many values to unpack (expected 2)
5 with * Number variable is not in a sequence, will also error
>>>*a ='spam'syntaxerror:starred Assignment target must beinchA listortuple>>>*a, ='spam' #that's OK .>>>a['s','P','a','m']
Augmented assignment
>>>spams = 42>>>spams + = 42>>>spams84
Augmented assignment has 3 advantages:
1 simple, can be less typing, haha
2 in the form of x + = y, if x is a complex object, then augmented assignment only runs the code once for X, and if it is written as x = x + y, the code for x runs two times
3 in some cases, x+=y is an optimization
>>>l = [1, 2]>>>l = L + [3, 4] # This form of + will create a temporary, new list, and then copy the L and the array to be concatenated, Finally, this temporary, new list is assigned to L, inefficient >>>l[1, 2, 3, 4]>>>l = [1, 2]>>>l + = [3, 4] # This form directly changes L, does not create new objects, nor copies, high efficiency >>>l[1, 2, 3, 4]
Assignment syntax in Python