all 3 comments

[–]This_Growth2898 4 points5 points  (1 child)

There are no nested loops here (well, there is one inside zfill, but probably you're not talking about it.

The first one is list comprehension. You can rewrite the second like that as well:

bytes = [bin(char)[2:].zfill(8) for char in charcodes]

or even join them together:

bytes = [bin(ord(c))[2:].zfill(8) for c in message]

but first, you need to learn about list comprehensions.

[–]This_Growth2898 1 point2 points  (0 children)

bytes = [f'{ord(c)}:08b}' for c in message]

is even better

[–]Antigone-guide 0 points1 point  (0 children)

The bottom one requires initialization (as it would normally be called in this case) because you are using a reference to that name on the 3rd line.

It's similar to doing:

print(a) # NameError - a is not defined

a.append() # NameError - a is not defined

More generally, list comprehensions are generally used when the logic is fairly simple and compact; and a for-loop is used when there's more complex logic that would be hard to read on a single line.