0
mybin = b'abcdefghij'

a = ''.join([str(i) for i in mybin])  # Line 1
print (a)

a = ''.join(str(i) for i in mybin)    # Line 2
print (a)

Both print the same output. So what does the extra square bracket do in this case? And if it doesn't make a difference in this example, other are there other situations where this can make a difference?

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
user93353
  • 13,733
  • 8
  • 60
  • 122
  • 1
    `[str(i) for i in mybin]` is a list comprehension. `(str(i) for i in mybin)` is a generator expression. People tell me that it's faster to pass a list to `join` instead of a generator, but the effect is the same. – khelwood Mar 11 '21 at 10:58
  • `[str(i) for i in mybin]` is a list comprehension meaning that it creates a list passed to join. `(str(i) for i in mybin)` is a generator expression meaning it creates a generator. The syntax allows to lose one set of brackets with the generator. It is equivalent to `.join((str(i) for i in mybin))` – Mathieu Mar 11 '21 at 10:59
  • 2
    See [Generator expressions vs. list comprehensions](https://stackoverflow.com/q/47789/3890632) – khelwood Mar 11 '21 at 11:01

1 Answers1

0

You can find it out using a debugger and if you assign the code in question to a variable:

mybin = b'abcdefghij'

line1 = [str(i) for i in mybin]
a = ''.join(line1)  # Line 1
print(a)

line2 = (str(i) for i in mybin)
a = ''.join(line2)  # Line 2
print(a)

line1 is a list as a result from a list comprehension, line2 creates a generator.

Screenshot from PyCharm:

Debugger

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222