0

I've seen some snippets of python code in which a loop was written as follows:

someList = g.db.execute('SELECT title, body FROM posts')
posts = [dict(title=x[0],body=[1]) for x in someList.fetchAll()]

What is this kind of loop refered to as?

I realize it could be just refered to as a for loop, but the syntax it quite different from a c-based language (shorter and more productive), so I just wondered if have some other name written like this.

leeand00
  • 23,306
  • 34
  • 125
  • 265
  • 2
    This is a list comprehension. – Adam Smith Sep 17 '18 at 05:38
  • 2
    Please note it is defintely _not_ a loop, but rather a single expression, called a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). – Ray Toal Sep 17 '18 at 05:38
  • 1
    Generally, I see this type loops under comprehension, such as list comprehension or set comprehension. – kur ag Sep 17 '18 at 05:40

2 Answers2

8

It's called list comprehension in Python.

blhsing
  • 70,627
  • 6
  • 41
  • 76
1

This is list comprehension, these are equivalent:

[dict(title=x[0],body=[1]) for x in someList]

for x in someList:
    dict(title = x[0], body = [1])
vash_the_stampede
  • 4,274
  • 1
  • 5
  • 20