- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
*Memos:
- explains parameters and arguments.
- explains iterable unpacking in variable assignment.
- explains * for iterable unpacking in variable assignment.
- explains * for iterable unpacking in function.
- explains ** for dictionary unpacking.
- explains *args and **kwargs in function.
- explains [] and () for variables in variable assignment.
- explains [] and () for variables for statement.
- explains shallow copy and deep copy.
You can assign one or more values to one or more variables as shown below:
v = 5
print(v) # 5
v = 10
print(v) # 10
*str type cannot be changed by accessing each character so use and to do that.
v = "Orange"
print(v, v[0], v[1], v[2], v[3], v[4], v[5]) # Orange O r a n g e
v = "Lemon"
print(v, v[0], v[1], v[2], v[3], v[4]) # Lemon L e m o n
v[2] = "M" # TypeError: 'str' object does not support item assignment
# ---------------------------------------------------------------------- #
v = "Lemon"
print(v, v[0], v[1], v[2], v[3], v[4]) # Lemon L e m o n
v = list(v) # Change `str` type to `list` type.
print(v, v[0], v[1], v[2], v[3], v[4]) # ['L', 'e', 'm', 'o', 'n'] L e m o n
v[2] = "M"
print(v, v[0], v[1], v[2], v[3], v[4]) # ['L', 'e', 'M', 'o', 'n'] L e M o n
v = ''.join(v) # Change `list` type to `str` type.
print(v, v[0], v[1], v[2], v[3], v[4]) # LeMon L e M o n
# Equivalent
v1 = v2 = v3 = 5 # v1 = 5
# v2 = v1
# v3 = v2
print(v1, v2, v3) # 5, 5, 5
v2 = 10
print(v1, v2, v3) # 5, 10, 5
*The reference of a list is stored in a variable so the variables v1, v2 and v3 have the same references of the same list, that's why changing the list content of v2 also changes the other list content of v1 and v3.
# Equivalent
v1 = v2 = v3 = ['a', 'b', 'c', 'd'] # v1 = ['a', 'b', 'c', 'd']
# v2 = v1
# v3 = v2
print(v1, v2, v3)
# ['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd']
v2[2] = 'X' # Changes the same list content by the same reference as v1 and v3.
print(v1, v2, v3)
# ['a', 'b', 'X', 'd'] ['a', 'b', 'X', 'd'] ['a', 'b', 'X', 'd']
v2 = list(v2) # v2 has the different reference of the different list
# from v1 and v3.
v2[2] = 'Y' # Changes a different list content by the different reference
# from v1 and v3.
print(v1, v2, v3)
# ['a', 'b', 'X', 'd'] ['a', 'b', 'Y', 'd'] ['a', 'b', 'X', 'd']
v3 = 'Z' # Changes a list reference itself.
print(v1, v2, v3)
# ['a', 'b', 'X', 'd'] ['a', 'b', 'Y', 'd'] Z
*The one or more values with one or more commas(,) are a tuple.
v = 'a', 'b', 'c' # Tuple
v = ('a', 'b', 'c') # Tuple
print(v, v[0], v[1], v[2]) # ('a', 'b', 'c') a b c