2

Say you write bytes(10), from my understanding, this will create a byte array with 10 bytes; however if you were to instead write bytes([10]) you would get the binary value of 10.

What effect do square brackets have on the datatype of a number? I cannot find any information on them as an operator.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Kalcifer
  • 1,211
  • 12
  • 18
  • 1
    It has nothing to do with numbers in particular, that's how you construct a list. `["hello"]` would likewise be a list containing a single string. – jasonharper Aug 13 '21 at 04:42
  • It will be considered as list you can check with `type([9])` output will be `` – MrBhuyan Aug 13 '21 at 04:47
  • "I cannot find any information on them as an operator." I got to the linked duplicate by putting `square brackets python` [into a search engine](https://duckduckgo.com/?q=square+brackets+python), checking the first link (which was to a Stack Overflow question) and following to the duplicate of [*that* one](https://stackoverflow.com/questions/46675477/in-python-when-to-use-a-square-or-round-brackets). The reason you won't find square brackets on a list of Python operators is the same reason you won't find double or single quotes - it's part of a *literal syntax*. – Karl Knechtel Aug 13 '21 at 04:55
  • Also, as @MrBhuyan indicates, Python has type introspection built in, so that's the first place to check. – Karl Knechtel Aug 13 '21 at 04:57

1 Answers1

5

[10] is a list literal. It creates a list with a single element, and that element is 10.

bytes() behaves in several different ways depending on the argument, as you can see from its help() documentation:

class bytes(object)
 |  bytes(iterable_of_ints) -> bytes
 |  bytes(string, encoding[, errors]) -> bytes
 |  bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
 |  bytes(int) -> bytes object of size given by the parameter initialized with null bytes
 |  bytes() -> empty bytes object
 |  
 |  Construct an immutable array of bytes from:
 |    - an iterable yielding integers in range(256)
 |    - a text string encoded using the specified encoding
 |    - any object implementing the buffer API.
 |    - an integer

In this case, [10] is used to invoke the bytes(iterable_of_ints) behavior rather than the bytes(int) behavior, despite only representing one byte.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53