본문 바로가기

스터디 로그/Computer Science

[Python] *args, **kwargs, and return vs. yield (Generator)

*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

 

*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