Skip to content
Search

Python:Comprehension

lastmod 2020-11-24created 2020-06-123 edits

A comprehension is one way to create an iterable object, and one of the useful features available in Python.

List Comprehension (LC)

A list comprehension is a way to create lists easily.

Set Comprehension (SC)

A set comprehension is exactly the same as an LC; the only difference is that it creates a set instead of a list.

Dict Comprehension (DC)

A dict comprehension is also the same as an LC, and creates a dict.

Generator Expression (GE)

A generator expression is a special form of comprehension. It creates a generator that returns one element at a time instead of all elements at once.

Example

Using a conditional inside a for statement creates a 2-depth block.

mylist = [3, 2, 6, 7]
answer = []
for i in mylist:
    if i%2 == 0:
        answer.append(i**2) # 들여쓰기를 두 번 함

With Python's list comprehension, you can handle a for statement and an if statement at once in a single line.

mylist = [3, 2, 6, 7]
answer = [ i**2 for i in mylist if i %2 == 0]

See also

Favorite site

author Zer0 sitemap