[Python](EN) Python List Comprehensions

Practice Python List Comprehensions


Environment and Prerequisite

  • Linux
  • Python 3.X.X


Python List Comprehensions

List Comprehensions

results=[]
for i in range(10):
    results.append(i*2)
results=[x*2 for x in range(10)]
  • List Comprehensions: List comprehensions provide a concise way to create lists. It can make list much simpler.
  • It can be used when you make new list which is result of each element’s operation or subset elements of some conditions.


Format

list_name = [element_format for clause]
  • Cover with brackets([ ]), add element format in the front and add for clause in the end.
  • As like below example, we can also use nested for loop.


Examples

Square

results=[]
for i in range(10):
    results.append(i**2)
results=[x**2 for x in range(10)]

Make tuple

results=[]
for x in [1,3,5]:
    for y in [2,4,6]:
        results.append((x,y))
results=[(x,y) for x in [1,3,5] for y in [2,4,6]]

Use with function

from math import pi

results=[]
for i in range(1, 6):
    results.append(str(round(pi, i)))
from math import pi
results=[str(round(pi, i)) for i in range(1, 6)]

Nested loop

results=[]
for x in [1,2]:
    for y in [3,4]:
        for z in [5,6]:
            results.append((x,y,z))
results=[(x,y,z) for x in [1,2] for y in [3,4] for z in [5,6]]

Use with if statement

results=[]
for x in range(20):
    if x%2 == 0:
        results.append(x)
results=[x for x in range(20) if x%2 == 0]


Reference