*args
The special syntax *args in function definitions in Python is used to pass a non-keyworded, variable length of argument list.
**kwargs
The special syntax **kwargs in function definitions in Python is used to pass a key-worded, variable-length of argument list.
def myFunc(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
myFunc(val1 = "apple", v2 = "banana")
# output
v1 == apple
v2 == banana
print statement with "%"
%s for string
%d for integer
%f for floating point number
name = "John"
age = 30
height = 6.152
print("Name: %s, Age: %d, Height: %.2f" % (name, age, height))
# output
Name: John, Age: 30, Height: 6.15
return vs. yield
return sends a specified value to its caller whereras yield can produce a sequence of values. We should use yield when we want to iterate over a sequence but don't want to store the entire sequence in memory.
yield vs. yield from
yield returns from a simple generator function, yield from allows you to yield from another generator function.
Python generators
A generator function is defined just like a normal function, but whenever it needs to generate a value, it does so with yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.
We can access to its next yielded value with next() function.
Next topic to study
- More about generators
- Generators vs. Iterators
References GeeksforGeeks
- https://www.geeksforgeeks.org/args-kwargs-python/?ref=lbp
- https://www.geeksforgeeks.org/use-yield-keyword-instead-return-keyword-python/?ref=lbp
- https://pythonalgos.com/2021/12/25/generator-functions-yield-and-yield-from-in-python/#:~:text=There's%20yield%20and%20yield%20from,in%20the%20sorting%20animations%20post.
*args and **kwargs in Python - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
When to use yield instead of return in Python? - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
'스터디 로그 > Computer Science' 카테고리의 다른 글
[LeetCode] 560. Subarray Sum Equals K (1) | 2024.02.08 |
---|---|
[LeetCode] 128. Longest Consecutive Sequence (0) | 2024.02.08 |
[Robotics] Sensor Fusion, Autonomous Systems (2) | 2023.10.30 |
[LeetCode] 53. Maximum Subarray (0) | 2023.07.29 |
[C] C언어의 무기, 포인터 (1) | 2023.01.29 |