DEV Community

Timothy Huang
Timothy Huang

Posted on • Updated on

List comprehension in Python

Sometimes we need a list with a serial integers, we can use the list comprehension syntax to generate a list with a serial integers like:

a = [ x for x in range(0,100) ]
# a = [0, 1, 2, ... 99]

If we need a list with some condition, like even numbers. We can also use the list comprehension syntax to generate a list with even numbers, like:

a = [ x for x in range(0, 100) if x % 2 == 0]
# a = [0, 2, 4, ... 98]

Another case we need a list with tuple like 2-dimension coordinate:

a = [ (x, y) for x in range(1, 6) for y in range(3, 6) ]
# a = [ (1, 3), (1, 4), (1, 5), (2, 3), (2, 4) ... ] 
## total 5 * 3 items 

But if we need the value pairs with both index with x, y move simultaneously, we can use zip:

a = [ x for x in zip(range(1, 6), range(3, 6)) ]
# a = [(1, 3), (2, 4), (3, 5)]
## total 3 items, because the range(3, 6)

The same usage with list comprehension, set and dictionary also has their comprehension.

set comprehension:

s = { v for v in 'ABCDE' }
# s = {'D', 'C', 'A', 'B', 'E'}

with some condition:

s = { v for v in 'ABCDE' if v not in 'BC' }
# {'D', 'E', 'A'}

dictionary comprehension:

s = {key: val for key, val in enumerate('ABCDEF')}
# s = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F'}

with some condition:

s = {key: val for key, val in enumerate('ABCDEF') if val not in 'CD'}
# s = {0: 'A', 1: 'B', 4: 'E', 5: 'F'}

with some condition (more complex):

s = {key: val for key, val in enumerate('ABCDEF') if (val not in 'CD') & (key != 0)}
# s = {1: 'B', 4: 'E', 5: 'F'}

After these example, we can understand the list comprehension to generate list and other types of data.

It's simple but important!

Happy coding!

Reference: https://en.wikipedia.org/wiki/List_comprehension

Discussion (0)