Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Generator Expressions Instead of List Comprehensions #1039

Merged

Conversation

denniszelada
Copy link
Contributor

In Python, when we use list comprehensions, it's like we've created the entire pile of apples and asked the interpreter to hold onto it. Sometimes, a better practice involves using generator expressions, which create iterators that yield objects one at a time. For large data sets, this can turn a slow, memory-intensive operation into a relatively fast one. What do you think?

Using generator expressions instead of list comprehensions can lead to better performance. This is especially true for functions such as anywhere it's not always necessary to evaluate the entire list before returning. For other functions such as max or sum it means that the program does not need to store the entire list in memory. These performance effects become more noticeable as the sizes of the lists involved grow larger.

This codemod replaces the use of a list comprehension expression with a generator expression within certain function calls. Generators allow for lazy evaluation of the iterator, which can have performance benefits.

The changes from this code look like this:

- result = sum([x for x in range(1000)])
+ result = sum(x for x in range(1000))

References:

Copy link
Member

@mmabrouk mmabrouk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR @denniszelada !

@mmabrouk mmabrouk merged commit a19734e into Agenta-AI:main Dec 12, 2023
2 of 3 checks passed
@mmabrouk
Copy link
Member

@all-contributors please add @denniszelada for code

Copy link
Contributor

@mmabrouk

I've put up a pull request to add @denniszelada! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants