What is the difference between a generator and list in Python

sanju saini
2 min readMar 24, 2023

--

In Python, a list is a built-in data structure that holds a collection of items in a specific order. It allows for indexing, slicing, and iterating over the items in the list. A generator, on the other hand, is a function that produces a sequence of values using the yield keyword, which suspends the function's execution and returns the value to the caller.

The main difference between a generator and a list is how they store and generate their values. A list stores all its values in memory at once, whereas a generator produces its values on the fly, as they are requested. This means that a generator can be more memory-efficient than a list, especially when working with large datasets.

Here are some other key differences between a generator and a list:

  • Lists are mutable, meaning you can modify them after creation, whereas generators are immutable and their values cannot be modified once they are generated.
  • Lists can be indexed and sliced, whereas generators cannot be directly indexed or sliced. Instead, you can iterate over them using a for loop or convert them to a list using the list() function.
  • Lists can be iterated over multiple times, whereas generators can only be iterated over once. Once a generator has been exhausted, you cannot iterate over it again.

In summary, generators are a more memory-efficient way to generate sequences of values in Python, especially when dealing with large datasets. However, they are not as flexible as lists and cannot be directly indexed or sliced.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

sanju saini
sanju saini

Written by sanju saini

Senior Software Engineer with 4.5+ years of experience in full-stack development, specializing in Python, Golang, PHP, Django, FastAPI, React, and RESTful APIs.

No responses yet

Write a response