# bytes() function in Python

## Introduction

The `bytes()` function returns an ***immutable*** ***bytes*** object initialized with the given size and data. You can call it as an immutable version of the [bytearray() function](https://blog.ashutoshkrris.in/bytearray-function-in-python).

The syntax of `bytes()` function is:

```python
bytes(source, encoding, errors)
```

where:

*   `source` (optional) is used to initialize the array
*   `encoding` (optional) is the encoding in the case of strings
*   `errors` (optional) is the action to take when the encoding conversion fails in the case of strings

The `bytearray()` function returns a **bytes** object of the given size and initialization values, which is an immutable sequence of integers in the range `0 <= x < 256`.

## `source` Parameter

The `source` parameter can be used to initialize the byte array in the following ways:

#### **Case 1: String**

In the case of String, it is converted to bytes using `str.encode()`. In this case, we must also provide **encoding** and optionally **errors**.

```python
string = "I love iRead Blog."

arr1 = bytes(string, 'utf-8')
arr2 = bytes(string, 'utf-16')
arr3 = bytes(string, 'utf-32')
print(arr1)
print(arr2)
print(arr3)
```

Output:

```bash
b'I love iRead Blog.'
b'\xff\xfeI\x00 \x00l\x00o\x00v\x00e\x00 \x00i\x00R\x00e\x00a\x00d\x00 \x00B\x00l\x00o\x00g\x00.\x00'
b'\xff\xfe\x00\x00I\x00\x00\x00 \x00\x00\x00l\x00\x00\x00o\x00\x00\x00v\x00\x00\x00e\x00\x00\x00 \x00\x00\x00i\x00\x00\x00R\x00\x00\x00e\x00\x00\x00a\x00\x00\x00d\x00\x00\x00 \x00\x00\x00B\x00\x00\x00l\x00\x00\x00o\x00\x00\x00g\x00\x00\x00.\x00\x00\x00'
```

In the above example, we created the array of bytes of a string with different string encodings.

#### **Case 2: Integer**

In this case, an array of the given size is created and initialized with null values.

```python
arr_size = 3

arr = bytes(arr_size)
print(arr)

```

Output:

```bash
b'\x00\x00\x00'
```

#### **Case 3: Object**

In this case, a read-only buffer of the object will be used to initialize the byte array.

```python
b_arr = bytes(b"Hello World")  # b_arr is a bytes object

print(bytes(b_arr))

```

Output:

```bash
b'Hello World'
```

#### **Case 4: Iterable**

In this case, an array is created of the same size as that of the iterable and initialized with the elements of the iterable. However, the iterable range should be `0 <= x < 256`.

```python
list1 = [1, 2, 3, 4]
print(bytes(list1))
```

Output:

```bash
b'\x01\x02\x03\x04'
```

If the list includes number(s) greater than 256, we get an error.

```python
list2 = [8, 16, 128, 256, 512]
print(bytes(list2))
```

Output:

```bash
ValueError: bytes must be in range(0, 256)
```

#### **Case 5: No Source**

In this case, an array of size 0 is created.

```python
arr = bytes()
print(arr)

```

Output:

```bash
b''
```

## Conclusion

In this part, we learned about the Python `bytes()` function with the help of examples.
