0

The code in question that I do not fully understand is this:

[print(x) if x < 5 else None for x in [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]]

It outputs:

1
1
2
3

The code does not work without the square brackets so I'm wondering what its purpose is?

Mark
  • 90,562
  • 7
  • 108
  • 148
  • 9
    This is bad/obfuscated code, and whoever wrote it and inflicted it on a beginner is themselves bad. The square brackets make it a list comprehension, but this should not be written as a list comprehension. – Samwise Apr 30 '22 at 18:42
  • 6
    It is list comprehension, but people hate this kind of usage, because `print` has a "side effect", and the resulting list is of no use. If a book recommends this code, I believe it is safe to just throw the book away. – j1-lee Apr 30 '22 at 18:44
  • 1
    Better to pull the print out if you want this kind of pattern: `print(*(x for x in [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] if x <5), sep='\n')` and avoid creating a throw-away list. – Mark Apr 30 '22 at 18:45
  • Please read [this guide](https://stackoverflow.com/editing-help) to learn how to format code in your question. – Bill Apr 30 '22 at 18:46
  • @wjandrea I'm not convinced that just saying that this is list comprehension fully answers the OP's question. – EJoshuaS - Stand with Ukraine Apr 30 '22 at 18:52
  • @EJoshuaS OK, I added the "list comp for side effects" question as a duplicate. Is that better? – wjandrea Apr 30 '22 at 19:01

1 Answers1

1

As others have indicated, this is a rather ugly abuse of list comprehension to avoid writing a "normal" for loop.

Normally, you would use list comprehension to construct a list from some other collection, but in this case print doesn't return anything so the resulting list would be completely useless.

The [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] part is just an "ordinary" list - they just hardcoded the list and didn't put it in a variable before they used it.

  • OK so yes, I understand that this is list comprehension and the code may not be that great, but it was for an exercise which made us compress everything into one line of code. The code in question was a code I found in the comments because I didn't know how to compress my code into one line. – Albatross08 Apr 30 '22 at 19:51