Skip to content

Commit 472358e

Browse files
authored
Merge pull request #164 from galkk/patch-1
Updated comprehensions.rst to include generator comprehensions
2 parents 75d7140 + 6748a9c commit 472358e

1 file changed

Lines changed: 15 additions & 0 deletions

File tree

β€Žcomprehensions.rstβ€Ž

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ comprehensions are supported in both Python 2 and Python 3:
99
- list comprehensions
1010
- dictionary comprehensions
1111
- set comprehensions
12+
- generator comprehensions
1213

1314
We will discuss them one by one. Once you get the hang of using ``list``
1415
comprehensions then you can use any of them easily.
@@ -91,3 +92,17 @@ that they use braces ``{}``. Here is an example:
9192
squared = {x**2 for x in [1, 1, 2]}
9293
print(squared)
9394
# Output: {1, 4}
95+
96+
``generator`` comprehensions
97+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
98+
99+
They are also similar to list comprehensions. The only difference is that they don't allocate memory for the whole list but generate one item at a time, thus more memory effecient.
100+
101+
.. code:: python
102+
103+
multiples_gen = (i for i in range(30) if i % 3 == 0)
104+
print(multiples_gen)
105+
# Output: <generator object <genexpr> at 0x7fdaa8e407d8>
106+
for x in multiples_gen:
107+
print(x)
108+
# Outputs numbers

0 commit comments

Comments
 (0)