Rick
Rick

Reputation: 45311

What is an expression such as [d[k] for k in d] called?

Python newbie here.

In learning about Python I have come across some very nice, succinct bits of code such as:

[d[k] for k in d]

I can see immediately that there are lots of possibilities for these kinds of expressions ("these kinds" meaning contained inside a []).

I'm unsure of what this kind of expression is called, and so I am having trouble searching for information on how to use it. Would be great for some knowledgeable folks to direct me toward the part of the Python docs, or other resources, that discusses these, and perhaps provide some suggestions of how to effectively use them.

Upvotes: 1

Views: 3851

Answers (1)

user2555451
user2555451

Reputation:

The code you posted is an expression, not a statement.

It is commonly called a list comprehension and its basic structure is:

[item for item in iterable if condition]

where the if condition clause is optional. The result is a new list object created from the items in iterable (possibly filtered by if condition):

>>> [x for x in (1, 2, 3)]  # Get all items in the tuple (1, 2, 3).
[1, 2, 3]
>>> [x for x in (1, 2, 3) if x % 2]  # Only get the items where x % 2 is True.
[1, 3]
>>>

In addition, there are dictionary comprehensions:

{key:value for key, value in iterable if condition}

and set comprehensions:

{item for item in iterable if condition}

which each do the same thing as the list comprehension, but produce dictionaries or sets respectively.

Note however that you need Python 2.6 or greater to use these constructs.


A final tool that you should be aware of is a generator expression:

(item for item in iterable if condition)

Similar to the list comprehension, it creates a generator object which produces its items lazily (one at a time as they are needed):

>>> (x for x in (1, 2, 3))
<generator object <genexpr> at 0x02811A80>
>>> gen = (x for x in (1, 2, 3))
>>> next(gen)  # Advance the generator 1 position.
1
>>> next(gen)  # Advance the generator 1 position.
2
>>> next(gen)  # Advance the generator 1 position.
3
>>> next(gen)  # StopIteration is raised when there are no more items.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

Upvotes: 8

Related Questions