Python short course: Different types of comprehensions in Python

We described list comprehensions basic before. Some other types of comprehensions are below.

Frist we build a matrix M

In [1]: M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


In [2]: M
Out[2]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Then, comprehensions in [] will get a list, while get a generator in (). For example,


In [3]: G = (sum(row) for row in M)

In [4]: next(G)
Out[4]: 6

In [5]: next(G)
Out[5]: 15

In [6]: next(G)
Out[6]: 24

and will get a set while in {}. Note that set will remove the duplications.


In [7]: {ord(i_str) for i_str in 'spaaam'}
Out[7]: {97, 109, 112, 115}

Comments

Popular posts from this blog

Lab's weekly topic - week 50 2023 - Detailed explanation for encoder of U-Net

Lab's recommendation: Awesome books to learn machine learning and AI (continue updating)