0

Hi I found the below function on some website somewhere and just have a couple of questions. The function returns a diamond of n lines made from asterisks.

  1. Is that a concatenated for loop? Is that a thing you can do?
  2. What is going on in that f-string? How does '':*<{line*2+1} work?
def diamond(n):
    result = ""
    for line in list(range(n)) + list(reversed(range(n-1))):
        result += f"{'': <{n - line - 1}} {'':*<{line*2+1}}\n"

    return result
  • It's in the documentation. I don't want to copy-paste it into an answer so here's the link: https://docs.python.org/3/reference/lexical_analysis.html#f-strings – T Tse Jun 16 '20 at 08:42
  • What part of the loop are you referring to when you say "concatenated loop"? – Arcanefoam Jun 16 '20 at 08:56
  • the fstring is basically equivalent with `' ' * (n - line - 1) + '*' * (line*2+1) + "\n"` – Tibebes. M Jun 16 '20 at 09:00
  • also check [this docs](https://docs.python.org/3/library/string.html#formatspec) out to understand more – Tibebes. M Jun 16 '20 at 09:02
  • @Arcanefoam `for line in list(range(n)) + list(reversed(range(n-1))):` The part with the addition operator. What is the effect of using it this way? Would it be fair to say its syntax sugar for two for loops? – Max Phillips Jun 16 '20 at 09:02
  • @MaxPhillips as @bereal mentioned in his reply, the two lists will be concatenated, i.e. in python adding lists concatenate them; any expression between the `in` and the colon `:` will be evaluated before entering the loop, so you dont have two loops, just a single loop over the concatenated lists. – Arcanefoam Jun 16 '20 at 09:05

1 Answers1

3

Regarding the iteration: yes, it iterates over a concatenation of two ranges, but it's not the most optimal way to do it. Using itertools.chain() looks like a better choice.

For the formatting part: f"{'':*<{n}}" literally means "right-pad the empty string with * to the length of n characters". In other words, it's some cryptic way of saying '*' * n.

More generally, everything that goes after : defines the format in the format specification mini-language.

Overall, this is quite a bad piece of code, don't use it as an example.

bereal
  • 32,519
  • 6
  • 58
  • 104
  • Ah thanks that makes more sense! Could you give an different example of what the `:` and `<` operators are doing here though? Is the colon just a way of appending to a string? – Max Phillips Jun 16 '20 at 09:06
  • @MaxPhillips the format language is described [here](https://docs.python.org/3/library/string.html#format-specification-mini-language), but there's also a great site [PyFormat](https://pyformat.info/) that gives plenty of examples. – bereal Jun 16 '20 at 09:19
  • You're right that is a great website! Gonna take a closer look. – Max Phillips Jun 16 '20 at 09:24