Memory Efficient Python List Creation in Case of Generators
Last Updated :
26 Dec, 2024
Creating lists in Python can sometimes be memory intensive, especially when dealing with large amounts of data. In such cases, generators offer a solution to reduce memory usage.
In this article, we will look at How we can create a list by using generators.
What are Generators?
Generators in Python are iterable, allowing the creation of iterators in a memory-efficient manner. Unlike lists that store all elements in memory at once, generators produce values on the fly as requested. They are defined using a function with the "the " keyword, which temporarily suspends the function's state, allowing it to resume from where it left off when the next value is requested.
Using List Comprehension
List comprehension is a common and simple method for creating lists in Python. However, it can be memory-heavy when dealing with large data sets because it creates the entire list in memory at once. To optimize memory usage, we will look at using a generator instead.
Python
a = [i * 2 for i in range(10)]
print(a)
Output[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Using Generator Expression
A generator expression is similar to list comprehension but more memory efficient. Instead of generating all the items at once, a generator produces one item at a time. This reduces the memory footprint because it doesn’t store the entire list in memory.
Python
a = (i * 2 for i in range(10))
print(list(a))
Output[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
- In this case, a is not a list but a generator. We can use it just like a list but it won’t occupy all the memory. The generator will produce values only when we need them, making it very memory-efficient.
Using map()
map() is another useful tool that works like a generator when combined with functions. It applies a given function to all items in an iterable without storing the entire result at once.
Python
def multiply_by_two(x):
return x * 2
a = map(multiply_by_two, range(10))
print(list(a))
Output[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
For more complex use cases, we can use the itertools module, which provides many tools to handle iterators efficiently. For example, itertools.count() can be used to generate an infinite sequence of numbers, and itertools.islice() allows us to grab specific slices of data from an iterator without loading everything into memory.
Python
import itertools
a = itertools.islice(itertools.count(), 10)
print(list(a))
Output[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Similar Reads
How to Write Memory Efficient Loops in Python When you are working on projects with limited resources or dealing with large amounts of data, it is important to be mindful of how much memory your Python code is using. In Python, loops are fundamental parts of programs, and making them use less memory can make your code run faster. This article e
3 min read
Python | Size and element exponentiation of list Sometimes, while working with Python lists, we can have a problem in which we need to extend a list in a very customized way. We may have to repeat the contents of the list and while doing that, each time new list must be exponentiation of the original list. This incremental expansion has applicatio
4 min read
Create a List of Strings in Python Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
3 min read
Python - Custom dictionary initialization in list While working with Python, we can have a problem in which we need to initialize a list of a particular size with custom dictionaries. This task has itâs utility in web development to store records. Letâs discuss certain ways in which this task can be performed. Method #1 : Using {dict} + "*" operato
3 min read
Python | Return new list on element insertion The usual append method adds the new element in the original sequence and does not return any value. But sometimes we require to have a new list each time we add a new element to the list. This kind of problem is common in web development. Let's discuss certain ways in which this task can be perform
5 min read
Python | Frequency grouping of list elements Sometimes, while working with lists, we can have a problem in which we need to group element along with it's frequency in form of list of tuple. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is a brute force method to perform this particular task. In this
6 min read