Yields and List in Python

Yields and List in Python

In this article, i will compare two common ways to return a sequence of values from a function is using yield to create a generator and returning a list.

What is List returning?

Returning a list from a function is returning a sequence of values (list of integers, list of strings, etc). The caller receives the fully constructed and can iterate over it or manipulate it as needed.

def return_list(nums):
    res = []
    for i in range(nums):
        res.append(i)
    return res

my_list = return_list(5)
print(my_list) 
# Output: [0, 1, 2, 3, 4]        

What is yield?

yield is a keyword in Python used to create a generator. It allows a function return a value and pause its execution, saving its state for later resumption. When the function is called, it returns a generator object which can be iterated over to retrieve values one at a time.

def generate_numbers(nums):
    for i in range(nums):
        yield i

my_yield = generate_numbers(5)
for num in my_yield:
    print(num, end=' ')
#Output: 0 1 2 3 4         

What is the difference?

Memory usage:

  • yield: Generators created with yield are memory efficient. They produce items one at a time, only when required, which is ideal for large datasets
  • Returning a list: When returning a list from a function, the entire list is stored in memory.

Performance:

  • yield: Good for large datasets since because it don't require the entire dataset to be stored in memory
  • Returning a list: Large datasets may cause list-returning functions to slow, but they are good for situations where the complete sequence is needed up front.

Easy to use:

  • yield: Using yield can be more complex, might be less intuitive initially, and might not be friendly for beginners
  • Returning a list: Straightforward, providing a complete dataset for immediate use.

Conclusion

Choosing the right method depends on the specific requirements of your tasks, particularly regarding memory usage, performance, and ease of use. Understanding both methods is an important skill for any Python developer.

Very helpfull! Thanks.

要查看或添加评论,请登录

Bùi Minh Hoàng的更多文章

  • Rank in MySQL

    Rank in MySQL

    Introduction to MySQL RANK() function The RANK() fucntion assigns a rank to each row within the partition of a result…

  • Fuzzy Search in Django with PostgreSQL

    Fuzzy Search in Django with PostgreSQL

    In real life, sometimes we want to search football but have the wrong typo, like footbal or fotball, but Google or…

    2 条评论
  • Why does offset make your query slow?

    Why does offset make your query slow?

    When working with Pagination, whenever i receive an API request with a URL like: /employee?page=10&count=10, my sql…

    4 条评论
  • Setup Redis Replication

    Setup Redis Replication

    In this article, i will setup Redis replication with 1 master and 3 replicas. First, create the project folder: RedisM…

    6 条评论
  • Composite index and include columns in PostgreSQL

    Composite index and include columns in PostgreSQL

    In PostgresSQL, both composite indexes and indexes with included columns are used to enhance query performance, but…

    7 条评论
  • Django ORM: prefetch_related

    Django ORM: prefetch_related

    In previous article, i mentioned select_related to minimize time hit database in Django, so in this article, i addition…

    1 条评论
  • Django ORM select_related.

    Django ORM select_related.

    In Django, select_related are designed to stop the deluge of database queries that are caused by accessing related…

  • Pessimitic locking and Optimistic locking in Django: Managing concurrent transactions

    Pessimitic locking and Optimistic locking in Django: Managing concurrent transactions

    In previous article, i mentioned using select_for_update() to solve concurrent transactions. select_for_update() can be…

    6 条评论
  • Using select_for_update() to solve concurrent transactions

    Using select_for_update() to solve concurrent transactions

    The Bank Account Transfer Problem A classic example of concurrent transaction issues is the bank account transfer…

    5 条评论
  • Transaction in Django ORM

    Transaction in Django ORM

    Django’s default behavior is to run in autocommit mode. Each query is immediately committed to the database, unless a…

    1 条评论