After all, what is a tuple?
Basically, you can think of it as a list whose contents cannot be changed. important point
--The contents of the objects in the tuple can be changed. -Declared with (), but it is recognized as a tuple even if it is separated by a comma.
Looking at the sample code, it was quick to understand.
t = (1, 2, 3)
# t[0] =0 Cannot be changed (cannot append)
#You can put an object and change the contents
t = (1, [1, 2])
t[1][0] = 0
print(t) # (1, [0, 2])
t = 1, 2, 3 #Recognized as tuples separated by commas
print(type(t)) # <class 'tuple'>
# (1)Note that is just a number. If you want to make tuples(1,)
#Tuple packing
t = (1, 2, 3)
#Tuple unpacking
x, y, z = t
print(x, y, z) # 1 2 3
#Can be replaced without tmp
x, y = y, x
print(x, y) # 2 1
Based on the above, you can think of it as a method of receiving variable arguments as tuples.
This was also quick to understand when looking at the sample code.
#Tuples are the remaining arguments, dictionaries are keyword arguments
def menu(food, *args, **kwargs):
print(f'food: {food}')
print(f'args: {args}')
for a in args:
print(a)
print(f'kwargs: {kwargs}')
for k, v in kwargs.items():
print(k, '=', v)
menu('banana', 'apple', 'orange', entree='beef', drink='coffee')
# food: banana
# args: ('apple', 'orange')
# apple
# orange
# kwargs: {'entree': 'beef', 'drink': 'coffee'}
# entree = beef
# drink = coffee
#This is a tuple and a dictionary* **Write using
t = ('apple', 'orange')
d = {'entree': 'beef', 'drink': 'coffee'}
menu('banana', *t, **d)
#Output is the same as above
#By the way* **Must be used*It will be recognized by args
menu('banana', t, d)
# food: banana
# args: (('apple', 'orange'), {'entree': 'beef', 'drink': 'coffee'})
# ('apple', 'orange')
# {'entree': 'beef', 'drink': 'coffee'}
# kwargs: {}
I did a dict with a lot of momentum, but what I was doing was the same.
Recommended Posts