2

what-is-the-meaning-of-curly-braces says that they are used for dictionaries, but what about this example?

resp = {
    requests.get('http://localhost:8000')
    for i in range(20)
}

Taken from here (actually it uses [], but it works with {} as well). What is the meaning of this, and why is this loop upside-down?

Georgy
  • 12,464
  • 7
  • 65
  • 73
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124

1 Answers1

6

Curly braces are also used for sets. This is a set comprehension. It creates the set of 20 requests.get objects, keeping only the unique ones.

If you use [] instead of {} it is a list comprehension. They are similar, but have two differences

  • the list is ordered
  • the list can have duplicate elements

Also, as you mention, this is a bad way to make requests. Comprehensions should be used for creating a list/set, not for calling a number of commands as a by-product. In that case, a simple for-loop is better, it makes the intent clearer.

blue_note
  • 27,712
  • 9
  • 72
  • 90
  • Thanks... I got confused because this is a very weird way to make these calls since their return values are saved in the set but not used afterwards. Also, I always write *-comprehensions in one line, so that threw me off a bit – CIsForCookies Oct 04 '18 at 08:09