**paste()**

and **cat()**

methods.
In this tutorial, let us explore the various methods available to concatenate strings in r and how to use these methods with examples.

String concatenation is a process of joining two or more strings into a single string. R language provides two different methods for string concatenation.

** paste()** method is the most common and widely used method for string concatenation in R.

The ** paste()** method can take multiple strings as input, combine them, and return a concatenated string as an output.

**Syntax**

`paste(string1, string2, …stringn, sep = “”, collapse=NULL)`

**Parameters**

**string1, string2, …stringn:**Input strings that need to be concatenated.**sep:**The separator that needs to be appended during the concatenation. If you don’t pass this argument, it will take space as the default separator.**collapse:**an optional character string to separate the results.

The `paste()`

method accepts two or more strings as input and returns a concatenated string as output.

```
output1 <- paste("R","Programming")
output2 <- paste("R","Programming","is","fun")
output1
output2
```

**Output**

```
"R Programming"
"R Programming is fun"
```

In the first example, we did not pass a value to `sep`

the argument and it used a default separator as whitespace while concatenating the string.

Let us extend our example to see how to pass a separator argument and concatenate the string in R.

```
output1 <- paste("R","Programming",sep = '-')
output2 <- paste("R","Python", "NumPy","Pandas",sep = ',')
output1
output2
```

**Output**

```
"R-Programming"
"R,Python,NumPy,Pandas"
```

The ** cat()** method works similarly to the

**paste()**

method. It can perform a character-wise concatenation and print the concatenated string as output, and also we can save the concatenated string into a file.**Syntax**

```
cat(… , file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE)
```

**Parameters**

**…**: R objects to concatenate**file**The name of the file where the output is printed**(optional)**:- sep
The separator that needs to be appended during the concatenation. If you don’t pass this argument, it will take space as the default separator.**(optional)**: **fill**A logical or positive numeric which represents how the output will be broken into successive lines. The default value is false.**(optional)**:**labels**A character vector of labels for the lines printed. Ignored if**(optional)**:`fill`

is`FALSE`

.**append**Required when you print the output to the file. If we pass ‘**(optional)**:`TRUE`

‘ the output will be appended to the file otherwise it will overwrite the contents of the file.

The `cat()`

method accepts two or more objects as input and returns a concatenated string as output.

```
firstName <- "Chandler"
middleName <- "R"
lastName <- "Bing"
cat(firstName, middleName, lastName)
```

**Output**

`Chandler R Bing`

In the below example, we use the `cat()`

method to concatenate two or more string objects and use a custom separator.

```
firstName <- "Chandler"
middleName <- "R"
lastName <- "Bing"
cat(firstName, middleName, lastName, sep = "-")
cat(firstName, middleName, lastName, sep = ",")
```

**Output**

```
Chandler-R-Bing
Chandler,R,Bing
```

In the below example, we use the `cat()`

method to concatenate two or more string objects and output the results to the CSV files, Text files, or any other file format.

The name.txt file gets created in the working directory.

```
firstName <- "Chandler"
middleName <- "R"
lastName <- "Bing"
cat(firstName, middleName, lastName, sep ="\n", file="name.txt")
```

**Output**

In the below example, we use the `cat()`

method to concatenate two or more string objects and append the results to the file.

The name.txt file gets created in the working directory.

```
firstName <- "Ross"
middleName <- "P"
lastName <- "Taylor"
cat(firstName, middleName, lastName, sep ="\n", file="name.txt" , append=TRUE)
```

Output

String concatenation is a process of joining two or more strings into a single string. We can perform string concatenation in R using the `paste()`

and `cat()`

methods.

`numpy.median()`

If the data set has an odd number of observations, the middle value is selected as a median. For example, the following list of seven numbers,1, 3, 3, **6**, 7, 8, 9 will have a median of *6*, which is the fourth value since the list has an odd count.

If the data set has an even number of observations, there is no distinct middle value and the median is usually defined to be the arithmetic mean of the two middle values. For example, this data set of 8 numbers1, 2, 3, **4, 5**, 6, 8, 9 has a median value of *4.5*, which is

The Syntax of ** numpy.median()** method is:

```
numpy.median(arr, axis=None, out=None, overwrite_input=True, keepdims=True)
```

The ** numpy.median()** method can take the following parameters.

**arr: nd_array**-the name of the input array**axis: {None or int or tuple of ints}**(**optional**) -the alignment or axis of the mean to be computed. The default is to compute the median along a flattened version of the array.**out: nd_array (optional**) – Alternate output`dtype`

in which the results are to be returned. The default value is.`None`

**overwrite_input: bool (optional**) – If the parameter is given as

then the compiler will allow the use of memory of the input array for calculations and the input array will be modified. The default value is**True**.`False`

**keepdims: bool (optional**) – If the value of`keepdims`

is set to

, then the axes which are reduced will be left in the result as dimensions with size one.**True**

The **numpy.median()** method will return a new array with median values.

- If the input contains integers or floats smaller than
`float64`

, the output data type returned is

.**np.float64** - Otherwise, the data type of the output is the same as that of the data type of the input.

The ** numpy.median()** method will compute the median of the array and returns the

**float64**

object as output.```
# import numpy to be used as np
import numpy as np
# initialize the array
array_in = np.arange(9).reshape(3, 3)
print("The input array is :")
print(array_in)
# median of the elements
array_out = np.median(array_in)
print("The median of the array is:",array_out)
print(type(array_out))
```

Output

```
The input array is :
[[0 1 2]
[3 4 5]
[6 7 8]]
The median of the array is:4.0
<class 'numpy.float64'>
```

When the **axis** parameter is specified as ** axis = 0**, then the

```
# import the numpy module
import numpy as np
# initialize the input array
array_in = [[15, 25, 30], [35, 55, 70]]
print("The input numpy array is:\n", array_in)
# the mean of the array as
print(
"The median of the array in column-major is:\n",
np.median(array_in, axis=0),
np.median(array_in, axis=0).shape,
type(np.median(array_in, axis=0)),
)
```

Output

```
The input numpy array is:
[[15, 25, 30], [35, 55, 70]]
The median of the array in column-major is:
[25. 40. 50.] (3,) <class 'numpy.ndarray'>
```

When the **axis** parameter is specified as ** axis = 1**, then the

```
# import the numpy module
import numpy as np
# initialize the input array
array_in = [[15, 25, 30], [35, 55, 70]]
print("The input numpy array is:\n", array_in)
# the mean of the array as
print(
"The median of the array in row-major is:\n",
np.median(array_in, axis=1),
np.median(array_in, axis=1).shape,
)
```

Output

```
The input numpy array is:
[[15, 25, 30], [35, 55, 70]]
The median of the array in row-major is:
[25. 55.] (2,)
```

We can compute the median of an Array in NumPy using the ** numpy.median() **method, it computes the median of an array in sorted order on a specified axis and returns the new meidan array elements.

**Reference**: NumPy Library

`numpy.__version__`

This guide will look at various ways to get the NumPy version. Let us look at each of the approaches using code examples.

`__version__`

attributeThe easiest and Pythonic way to get the NumPy version is by using the ** __version__** attribute. This is the standard way to check the version of any standard Python libraries.

```
import numpy
print(numpy.__version__)
```

Output

`1.21.6`

If you need detailed information on the NumPy version, then we can use

. The **np.version**** version.py** file gets generated using

`setup.py`

```
import numpy as np
print(np.version.version)
print(np.version.short_version)
print(np.version.full_version)
print(np.version.git_revision)
print(np.version.release)
```

Output

```
1.21.6
1.21.6
1.21.6
ef0ec786fd4c7622ad2fa0e54d3881f3b9bbd792
True
```

Note:The version, short_version, full_version will have the same value. If it's not a release version then the git_revision is added to the version and full_version.

We can use the ** pip3** command to get the NumPy version. There are multiple ways to get the NumPy version using the

The ** pip3 list** command will list all the packages installed in your system or virtual environment.

`pip3 list`

Output

```
numpy 1.21.6
openpyxl 3.0.10
pandas 1.1.5
```

Instead of listing all the packages, you can find the NumPy package by using the command

```
>> pip3 list | FINDSTR numpy
numpy 1.21.6
```

**On Linux**

```
$ pip list | grep numpy
numpy 1.21.6
```

The second approach is to use the ** pip3 show** command. It will provide complete information(version, author, installation path, license, etc.) on NumPy if installed on your machine or virtual environment.

`pip3 show numpy`

Output

```
Name: numpy
Version: 1.21.6
Summary: NumPy is the fundamental package for array computing with Python.
Home-page: https://www.numpy.org
Author: Travis E. Oliphant et al.
Author-email:
License: BSD
Location: c:\users\m1014107\appdata\local\programs\python\python37\lib\site-packages
Requires:
Required-by: pandas
```

The third approach is to use ** pip3 freeze** to get any Python package version without opening the Python shell.

```
>> pip freeze | FINDSTR 'numpy'
numpy==1.21.6
```

**On Linux**

```
$ pip freeze | grep 'numpy'
numpy==1.21.6
```

We can get the NumPy version in the Anaconda distribution using the ** conda **command. Open the Anaconda prompt and type the below command.

`conda list numpy`

Output

```
# Name Version Build Channel
numpy 1.21.6 py38h34a8a5c_0
numpy-base 1.21.6 py38haf7ebc8_0
numpydoc 1.1.6 pyhd3eb1b0_1
```

`conda list | grep numpy`

Output

```
numpy 1.21.6 py38h7241aed_0
numpy-base 1.21.6 py38h6575580_1
numpydoc 1.1.6 py_0
```

The other alternate way is to use the command line and print the NumPy version, as shown below.

```
python3 -c "import numpy; print(numpy.__version__)"
python -c "import numpy; print(numpy.__version__)"
```

Output

`1.21.6`

There are multiple ways to check the NumPy version; the Pythonic and PEP8 standard ways are to use the ** numpy.__version__** attribute. Alternatively, we can also use the

`pip3`

`numpy.ndarray.flatten()`

The flattening of a **NumPy** n-dimensional array in python is a procedure to return a copy of an array that is collapsed to a one-dimensional NumPy array.

The flattening of the NumPy array can be done in **4** different orders, those are:

**C-style or Row-Major style Order**: the ordering of consecutive row elements residing next to each other.**F-Style (Fortran Style) or Column-Major Order:**the ordering of consecutive column elements residing next to each other.**A-style**: The ordering can be two types here.- 1) column-major order if the NumPy array is Fortran Contiguous
- 2)Row-Major order if the NumPy array is Fortran Non-Contiguous.

**K-Style Order**: flatten in the order that elements occur in memory.

The method will return a copy of the original array. Since the n-dimensional output array is a copy of the original NumPy array, changing the output array will not affect the value of the original NumPy array.

`numpy.ndarray.flatten()`

The syntax of method is:

`numpy.ndarray.flatten()`

```
ndarray.flatten(order='C')
```

The ** numpy.ndarray.flatten()** method takes a single optional argument.

**order: {‘C’, ’F’, ‘A’, ’K’}: (Optional)**– the type of order of flattening which can be any of the values as follows {‘C’, ’F’, ’A’, ’K’}. If no value is provided it takes the default value ‘C’ which is row-major style order.

The method ** ndarray.flatten()** returns a copy of a 1-dimensional array with the same type of elements.

The method ** ndarray.flatten()** flattens the input array into a single-dimensional array. If the

**order**

argument is not provided or if the `order`

value is passed as `None`

```
import numpy as np
# initialize the numpy n-D array
arr_in = np.array([[[2, 17], [45, 78]], [[88, 92], [60, 76]], [[76, 33], [20, 18]]])
print("The input array is:\n", arr_in)
print("The flattened numpy array in default order(C-style order) is:")
# flatten function will flatten input array to default ordering(C-)
print(arr_in.flatten())
```

Output

```
The input array is:
[[[ 2 17]
[45 78]]
[[88 92]
[60 76]]
[[76 33]
[20 18]]]
The flattened numpy array in default order(C-style order) is:
[ 2 17 45 78 88 92 60 76 76 33 20 18]
```

If we pass

as an argument for the method **order='C'**** ndarray.flatten()**, the method flattens the input array into a single-dimensional array and returns the array in row-major order style.

```
import numpy as np
# initialize the numpy n-D array
arr_in = np.array([[[2, 17], [45, 78]], [[88, 92], [60, 76]], [[76, 33], [20, 18]]])
print("The input array is:\n", arr_in)
print(
"The flattened numpy array in Row major order(C-style order) using order = 'C' is:"
)
# flatten row major ordering using order = 'C'
print(arr_in.flatten(order="C"))
```

Output

```
The input array is:
[[[ 2 17]
[45 78]]
[[88 92]
[60 76]]
[[76 33]
[20 18]]]
The flattened numpy array in Row major order(C-style order) using order = 'C' is:
[ 2 17 45 78 88 92 60 76 76 33 20 18]
```

If we pass

as an argument for the method **order='F'**** ndarray.flatten()**, the method flattens the input array into a single-dimensional array and returns the array in column-major order style also called as F-Style (Fortan Style).

```
import numpy as np
# initialize the numpy n-D array
arr_in = np.array([[[2, 17], [45, 78]], [[88, 92], [60, 76]], [[76, 33], [20, 18]]])
print("The input array is:\n", arr_in)
print(
"The flattened numpy array using fortran order(Column major order) using order = 'F' is:"
)
# flatten fortran ordering using order = 'F'
print(arr_in.flatten(order="F"))
```

Output

```
The input array is:
[[[ 2 17]
[45 78]]
[[88 92]
[60 76]]
[[76 33]
[20 18]]]
The flattened numpy array using fortran order(Column major order) using order = 'F' is:
[ 2 88 76 45 60 20 17 92 33 78 76 18]
```

If we pass

as an argument for the method **order='A'**** ndarray.flatten()**, the method flattens the input array into a single-dimensional array and returns the array in Fortran contiguous ordering in memory.

```
import numpy as np
# initialize the numpy n-D array
arr_in = np.array([[[2, 17], [45, 78]], [[88, 92], [60, 76]], [[76, 33], [20, 18]]])
print("The input array is:\n", arr_in)
print(
"The flattened numpy array in column-major order if array is Fortran contiguous in memory using order = 'A'is:"
)
# flattening numpy array in column-major order if array is Fortran contiguous in memory
print(arr_in.flatten(order="A"))
```

Output

```
The input array is:
[[[ 2 17]
[45 78]]
[[88 92]
[60 76]]
[[76 33]
[20 18]]]
The flattened numpy array in column-major order if array is Fortran contiguous in memory using order = 'A'is:
[ 2 17 45 78 88 92 60 76 76 33 20 18]
```

If we pass

as an argument for the method **order='K'**** ndarray.flatten()**, the method flattens the input array into a single-dimensional array and returns the 1-D array as elements occur in memory either in contiguous or non-contiguous.

```
import numpy as np
# initialize the numpy n-D array
arr_in = np.array([[[2, 17], [45, 78]], [[88, 92], [60, 76]], [[76, 33], [20, 18]]])
print("The input array is:\n", arr_in)
print("The array is flattened to order of elements occurs in memory is:")
# flattened to order of elements occurs in memory
print(arr_in.flatten(order="K"))
```

Output

```
The input array is:
[[[ 2 17]
[45 78]]
[[88 92]
[60 76]]
[[76 33]
[20 18]]]
The array is flattened to order of elements occurs in memory is:
[ 2 17 45 78 88 92 60 76 76 33 20 18]
```

The flattening of a NumPy n-dimensional array in python is a procedure to return an array that is collapsed to a one-dimensional NumPy array. We use the ** numpy.ndarray.flatten()** function to flatten an array of elements in different orders.

**Reference**: NumPy Library

`numpy.mean()`

In **NumPy** array library or Mathematics, the **arithmetic mean** is the sum of the given elements along with an axis divided by the total number of elements. It is the average of the given numbers.

**For Example –** Imagine we have a NumPy array of five values as shown.

We can use the NumPy ** np.mean()** function to compute the mean of the Array as shown below.

The Syntax of ** numpy.mean()** method is:

`numpy.mean(array_name, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>)`

**array_name:**the name of the input array containing input numbers for which the mean needs to be computed.**axis: None or int or tuple of ints**(**optional**) – the alignment or axis of the mean to be computed. If None, the default is to compute the mean of the flattened array. If int or a tuple of ints, a mean is performed over multiple axes, instead of a single axis or all the axes as before.**dtype: [int, float64] (optional) –**Data Type to use in computing the mean, use ‘int’ for integer and ‘float64’ for floating point value.**out: nd_array (optional**) – Alternate output array in which the results are to be placed. The default is**None****keepdims: bool (optional**) – If the value of`keepdims`

is set to True, then the axes that are reduced will be left in the result as dimensions with size one.**where: array_like of bool (optional) –**Elements to be included in the mean.

The ** numpy.mean()** method will return a new array with mean values as the elements if

In the below example the ** numpy.mean()** function will compute the weighted mean of a NumPy n-dimensional array

`array_in`

```
# import the numpy module
import numpy as np
# initialize the input array
array_in = [[15, 25, 30], [35, 55, 70]]
print("The input numpy array is:\n", array_in)
# the mean of the array
print("The mean of the array in flattened is:\n", np.mean(array_in, axis=None))
```

**Output**

```
The input numpy array is:
[[15, 25, 30], [35, 55, 70]]
The mean of the array in flattened is:
38.333333333333336
```

When the

parameter is specified as **axis** ** axis = 0**, then the mean is computed on the column-major elements as shown in the below example.

```
# import the numpy module
import numpy as np
# initialize the input array
array_in = [[15, 25, 30], [35, 55, 70]]
print("The input numpy array is:\n", array_in)
# the mean of the array as
print("The mean of the array in column-major is:\n", np.mean(array_in, axis=0))
```

**Output**

```
The input numpy array is:
[[15, 25, 30], [35, 55, 70]]
The mean of the array in column-major is:
[25. 40. 50.]
```

When the

parameter is specified as **axis** ** axis = 1**, then the mean is computed on the row-major elements as shown in the below example.

```
# import the numpy module
import numpy as np
# initialize the input array
array_in = [[15, 25, 30], [35, 55, 70]]
print("The input numpy array is:\n", array_in)
# the mean of the array
print("The mean of the array in row-major is:\n", np.mean(array_in, axis=1))
```

**Output**

```
The input numpy array is:
[[15, 25, 30], [35, 55, 70]]
The mean of the array in row-major is:
[23.33333333 53.33333333]
```

When the

parameter is specified as **axis** ** axis = None**, then the array will be operated as flattened for calculating the mean of the elements.

```
import numpy as np
# initialize input array
array_in = [[1.0, 0.1], [1.5, 0.5]]
print("The input numpy array is:\n", array_in)
# the mean of the array as default float64 data_type
print("The array of means of the input array is:\n", np.mean(array_in, axis=1))
# using output data_type as float64
print(
"The array of means of the input array in float64 is:\n",
np.mean(array_in, axis=1, dtype=np.float64),
)
# using output data_type as float32
print(
"The array of means of the input array in float32 is:\n",
np.mean(array_in, axis=1, dtype=np.float32),
)
# using output data_type as int
print(
"The array of means of the input array in integer is:\n",
np.mean(array_in, axis=1, dtype=int),
)
```

**Output**

```
The input numpy array is:
[[1.0, 0.1], [1.5, 0.5]]
The array of means of the input array is:
[0.55 1. ]
The array of means of the input array in float64 is:
[0.55 1. ]
The array of means of the input array in float32 is:
[0.55 1. ]
The array of means of the input array in integer is:
[0 0]
```

When the ** axis** parameter is specified as

`axis=(0,1)`

```
import numpy as np
array_in = [[15, 25, 30], [35, 55, 70]]
print("The input numpy array is:\n", array_in)
# the mean of the array both row-major and column-major
array_out = np.mean(array_in, axis=(0, 1))
print(
"The mean of the array in both row-major and column-major and type of the output respectively are:\n",
array_out,
)
print(type(array_out))
```

**Output**

```
The input numpy array is:
[[15, 25, 30], [35, 55, 70]]
The mean of the array in both row-major and column-major and type of the output respectively are:
38.333333333333336
<class 'numpy.float64'>
```

If we provide the parameter ** where = [[True],[False],[False]]** then the

**numpy.mean()**

function will check the boolean array `[[True],[False],[False]]`

`True`

,```
import numpy as np
# initialize the input array
array_in = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
print("The input nd_array is:\n\n", array_in)
# flattened average of the input array
print("\nmean with every row is selected :\n\n", np.mean(array_in, axis=None))
# every dimension is selected
print(
"\nmean with every row is selected :\n\n",
np.mean(array_in, axis=None, where=[[True], [True], [True]]),
)
# only the first row is selected for average
print(
"\nmean with only the first row is selected :\n\n",
np.mean(array_in, axis=None, where=[[True], [False], [False]]),
)
# only the last row is selected for average
print(
"\nmean with only the last row is selected :\n\n",
np.mean(array_in, axis=None, where=[[False], [False], [True]]),
)
# only the first and second row is selected for average
print(
"\naverage with only the first and second row is selected :\n\n",
np.mean(array_in, axis=None, where=[[True], [True], [False]]),
)
```

**Output**

```
The input nd_array is:
[[ 5 9 13]
[14 10 12]
[11 15 19]]
mean with every row is selected :
12.0
mean with every row is selected :
12.0
mean with only the first row is selected :
9.0
mean with only the last row is selected :
15.0
average with only the first and second row is selected :
10.5
```

The

function is used to compute the arithmetic mean along the specified axis. The **numpy.mean()**`mean()`

function returns the new array with mean values as the elements if

, else a reference to the output NumPy array is returned.**out = None**

**Reference**: NumPy Library

`numpy.average()`

The **average** in linear algebra is the proportion of the sum of a given set of values to the total number of values according to their weightage.

The Syntax of ** numpy.average()** method is:

```
numpy.average(
array_name, axis=axis_type, weights=array_like, returned=bool, keepdims=bool
)
```

**array_name:**the name of the input array**axis: None or int or tuple of ints**(**optional) –**the alignment or axis of the**average**is to be computed**weights: array_like (optional**) – An array of weights with respect to the input array. The values in the input array will average according to the respective weightage. If the weight parameterthen all the weightage of input array values are equated to one.`weights = None`

,**returned: bool (optional**) – The default value is. If the value is`False`

, the tuple(`True`

**average, sum_of_weights)**is returned, else only the**average is returned.****keepdims: bool (optional) –**If the value ofis set to`keepdims`

, then the axes that are reduced will be left in the result as dimensions with size one.`True`

Note:The calculation for average is as follows:average = sum(array_name * weights)/sum(weights)

** numpy.average()** method returns the

`returned`

`True`

, : When all weights along the axis are zero.*ZeroDivisionError*: When the length of 1D*TypeError**weights*is not the same as the shape of`arr`

along axis.

** numpy.average()** will compute the weighted average of a numpy n-dimensional array

```
# import numpy to be used as np
import numpy as np
# initialize the input array
array_in = np.arange(20).reshape(2, 5, 2)
print("The input array of values:\n\n", array_in, "\n")
# average is calculated with default as flattened
average_final = np.average(array_in)
print(
"The average and type of the output average are:\nAverage =",
average_final,
",\nType of Output =",
type(average_final),
)
```

**Output**

```
The input array of values:
[[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]]
[[10 11]
[12 13]
[14 15]
[16 17]
[18 19]]]
The average and type of the output average are:
Average = 9.5 ,
Type of Output = <class 'numpy.float64'>
```

When the ** axis** parameter is specified as

`axis = 0`

```
# import numpy to be used as np
import numpy as np
# initialize the input array
array_in = np.arange(20).reshape(2, 5, 2)
print("The input array of values:\n\n", array_in, "\n")
# average is calculated with default as flattened
average_final = np.average(array_in, axis=0)
print(
"The average column-major and type of the output average are:\nAverage =\n",
average_final,
",\nType of Output =",
type(average_final),
)
```

Output

```
The input array of values:
[[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]]
[[10 11]
[12 13]
[14 15]
[16 17]
[18 19]]]
The average column-major and type of the output average are:
Average =
[[ 5. 6.]
[ 7. 8.]
[ 9. 10.]
[11. 12.]
[13. 14.]] ,
Type of Output = <class 'numpy.ndarray'>
```

When the ** axis** parameter is specified as

`axis = 1`

```
# import numpy to be used as np
import numpy as np
# initialize the input array
array_in = np.arange(20).reshape(2, 5, 2)
print("The input array of values:\n\n", array_in, "\n")
# average is calculated with default as flattened
average_final = np.average(array_in, axis=1)
print(
"The average row-major and type of the output average are:\nAverage =\n",
average_final,
",\nType of Output =",
type(average_final),
)
```

**Output**

```
The input array of values:
[[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]]
[[10 11]
[12 13]
[14 15]
[16 17]
[18 19]]]
The average row-major and type of the output average are:
Average =
[[ 4. 5.]
[14. 15.]] ,
Type of Output = <class 'numpy.ndarray'>
```

When the parameter

is specified as **returned** ** returned = True**, then the output of the average function will be a tuple of

```
# import numpy to be used as np
import numpy as np
# initialize the input array
array_in = np.arange(20).reshape(2, 5, 2)
# initialize the weighted array
weights_array = np.arange(20).reshape(2, 5, 2)
print("The input array is:\n\n", array_in, "\n")
print("The weighted array is:\n\n", weights_array)
# average with returned value as True
average_array = np.average(array_in, axis=1, weights=weights_array, returned=True)
print(
"\nThe tuple of arrays of average and sum_of_weights are as elements:\n\n",
average_array,
"\n",
)
# the output object is a tuple of (average, sum_of_weights)
print("\nThe type of output object is:\n\n", type(average_array))
# average array only
print("\nAverage array is:\n\n", average_array[0], "\n")
# sum_of_weights array only
print("\nsum_of_weights array is:\n\n", average_array[1])
```

**Output**

```
The input array is:
[[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]]
[[10 11]
[12 13]
[14 15]
[16 17]
[18 19]]]
The weighted array is:
[[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]]
[[10 11]
[12 13]
[14 15]
[16 17]
[18 19]]]
The tuple of arrays of average and sum_of_weights are as elements:
(array([[ 6. , 6.6 ],
[14.57142857, 15.53333333]]), array([[20., 25.],
[70., 75.]]))
The type of output object is:
<class 'tuple'>
Average array is:
[[ 6. 6.6 ]
[14.57142857 15.53333333]]
sum_of_weights array is:
[[20. 25.]
[70. 75.]]
```

The ** numpy.average()** function computes the weighted average of elements that are specified. If the argument

`returned`

`True`

, **Reference**: NumPy Library

`numpy.repeat()`

The syntax of ** numpy.repeat()** function is:

`numpy.repeat(`*a*, *repeats*, *axis=None*)

The ** numpy.repeat()** method can take 3 parameters:

**arr –**An array-like object as an input argument**repeats –**The number of repetitions for each element.**axis(optional) –**The axis along which to repeat the values. If, it uses the flattened input array and returns a flattened output array.`None`

The ** numpy.repeat()** method returns an array with the same shape as

In the below example, we are using the ** numpy.repeat()** method on the 1-Dimensional NumPy Array. The repetition occurs elements-wise, and each element gets repeated in the 1-D Array as shown.

```
from array import array
import numpy as np
# NumPy Array
arr = np.array([1, 2, 3])
# Prints original Array
print('Original Array\n', arr)
# repeat the 1-D array 2 times
new_arr = np.repeat(arr,2)
# print the NumPy Array
print('Repeating 1-D Array\n',new_arr)
```

Output

```
Original Array
[1 2 3]
Repeating 1-D Array
[1 1 2 2 3 3]
```

In the previous example, we saw the repetition happens element-wise instead of Array wise.

In the case of a 2-Dimensional Array, the ** numpy.repeat()** method will return a flattened array by default and then repeat the elements.

It means the arrays are first reshaped to single-dimensional before repeating. This happens because we are not passing the axis argument; by default, it takes as none and reshapes into 1-Dimensional Array.

```
from array import array
import numpy as np
# NumPy Array
arr = np.array([[1, 2, 3],[4,5,6]])
# Prints original Array
print('Original Array\n', arr)
# repeat the 2-D array 2 times
new_arr = np.repeat(arr,2)
# print the NumPy Array
print('Repeating 2-D Array\n',new_arr)
```

Output

```
Original Array
[[1 2 3]
[4 5 6]]
Repeating 2-D Array
[1 1 2 2 3 3 4 4 5 5 6 6]
```

In most cases, we do not want to flatten the multi-dimensional array; rather, we would need to repeat the array along the axis, i.e., either row-wise or column-wise.

In NumPy Array, the 0th axis represents the row; hence if we need to repeat the array row-wise, we need to pass ** 0** into the

`axis`

```
from array import array
import numpy as np
# NumPy Array
arr = np.array([[1, 2, 3],[4,5,6]])
# Prints original Array
print('Original Array\n', arr)
# repeat the 2-D array 2 times along row
new_arr = np.repeat(arr,2,axis=0)
# print the NumPy Array
print('Repeating 2-D Array Row Wise\n',new_arr)
```

Output

```
Original Array
[[1 2 3]
[4 5 6]]
Repeating 2-D Array Row Wise
[[1 2 3]
[1 2 3]
[4 5 6]
[4 5 6]]
```

In NumPy Array, the 1st axis represents the column; hence if we need to repeat the array column-wise, we need to pass ** 1** into the

**axis**

argument.```
from array import array
import numpy as np
# NumPy Array
arr = np.array([[1, 2, 3],[4,5,6]])
# Prints original Array
print('Original Array\n', arr)
# repeat the 2-D array 2 times along Column
new_arr = np.repeat(arr,2,axis=1)
# print the NumPy Array
print('Repeating 2-D Array Column Wise\n',new_arr)
```

Output

```
Original Array
[[1 2 3]
[4 5 6]]
Repeating 2-D Array Column Wise
[[1 1 2 2 3 3]
[4 4 5 5 6 6]]
```

The ** numpy.repeat()** function repeats the elements of an array along the given axis and returns the repeated array as output. By default, if we do not pass the

`axis`

If we have to repeat the Array row-wise then we need to pass

into the **0**** axis **parameter and for repeating column-wise we need to pass

**1**

into the `axis`

**Reference**: NumPy Library

**numpy.transpose()**

function takes the array as an input, reverses its dimension, and returns the transposed array. In simple terms, the NumPy transpose swaps from rows to columns and columns to rows and returns the modified array as output.
The syntax of

function is:**numpy.transpose()**

`numpy.transpose(`*arr*, *axes=None*)

The

method takes 2 parameters:**numpy.transpose()**

**arr –**An array-like object as an input argument**axes(optional) –**If specified, it must be a tuple or list which contains a permutation of [0,1,..,N-1] where N is the number of axes of arr. If not specified, defaults to range(a.ndim)[::-1], which reverses the order of the axes.

The

method takes an array as input. It reverses its dimension by moving rows data to columns and columns data to rows and returns the modified array as an output.**numpy.transpose()**

In the below example, we transpose the NumPy array using the

method.**numpy.transpose()**

```
import numpy as np
# NumPy Array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Prints original Array
print('Original Array\n', arr)
# Transposes rows to columns and columns to rows
transposed_arr = np.transpose(arr)
# print the Transposed NumPy Array
print('Transposed Array\n',transposed_arr)
```

Output

```
Original Array
[[1 2 3]
[4 5 6]]
Transposed Array
[[1 4]
[2 5]
[3 6]]
```

In the below example, we are specifying the axis parameter to transpose the array. This will permute the axes or interchange the rows and columns and returns the transposed array.

```
from array import array
import numpy as np
# NumPy Array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Prints original Array
print('Original Array\n', arr)
arr.strides
# Transposes rows to columns and columns to rows along axis
transposed_arr = np.transpose(arr, (1,0))
# print the Transposed NumPy Array
print('Transposed Array\n',transposed_arr)
```

Output

```
Original Array
[[1 2 3]
[4 5 6]]
Transposed Array
[[1 4]
[2 5]
[3 6]]
```

In this example, we are creating a NumPy array using the ** numpy.ones()** method and reposition the array elements using the

`numpy.transpose()`

method along with the shape.```
from array import array
import numpy as np
# NumPy Array
arr = np.ones((3,4,6,5))
# Transposes rows to columns and columns to rows
transposed_arr1 = np.transpose(arr, (1,0,2,3)).shape
transposed_arr2 = np.transpose(arr, (0,1,3,2)).shape
# print the Transposed NumPy Array Shape
print('Transposed Array Shape 1 \n',transposed_arr1)
print('Transposed Array Shape 2 \n',transposed_arr2)
```

Output

```
Transposed Array Shape 1
(4, 3, 6, 5)
Transposed Array Shape 2
(3, 4, 5, 6)
```

The ** numpy.transpose() **function transposes

**Reference**: NumPy Library

In Python, indentation is most important as it does not use curly braces syntax like other languages to denote where the code block starts and ends.

Without indentation Python will not know which code to execute next or which statement belongs to which block and this will lead to ** IndentationError**.

We can indent the Python code either using spaces or tabs. The Python style guide recommends using spaces for indentation. Further, it states Python disallows mixing tabs and spaces for indentation and doing so will raise **Indentation Error**.

Let us look at an example to demonstrate the issue.

In the above example, we have a method `convert_meter_to_cm()`

, and the first line of code is indented with a tab, and the second line is indented with four white spaces.

```
def convert_meter_to_cm(num):
output = num * 1000
return output
convert_meter_to_cm(10)
```

Output

```
File "c:\Personal\IJS\Code\prgm.py", line 3
return output
^
TabError: inconsistent use of tabs and spaces in indentation
```

When we execute the program, it clearly shows what the error is and where it occurred with a line number.

We have used both spaces and tabs in the same code block, and hence we got the error in the first place. We can resolve the error by using either space or a tab in the code block.

Let us indent the code according to the PEP-8 recommendation in our example, i.e., using four white spaces everywhere.

```
def convert_meter_to_cm(num):
output = num * 1000
return output
print(convert_meter_to_cm(10))
```

Output

`10000`

If you are using the VS Code, the easy way to solve this error is by using the settings “Convert indentation to spaces” or “Convert indentation to tabs” commands.

- Press CTRL + Shift + P or (⌘ + Shift + P on Mac) to open the command palette.
- type “convert indentation to” in the search command palette
- select your preferred options, either tab or space

- Generally, in Python, you follow the four-spaces rule according to
**PEP 8 standards**. - Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs.
- Do not mix tabs and spaces. Python disallows the mixing of indentation.
- Avoid trailing whitespaces anywhere because it’s usually invisible and it causes confusion.

If you mix both tabs and spaces for indentation in the same code block Python will throw **inconsistent use of tabs and spaces in indentation. **Python is very strict on indentation and we can use either white spaces or tabs in the same code block to resolve the issue.

Lists are one of the four most commonly used data structures in Python, and it is mainly used to store data collection. There are multiple ways to find if the given list is empty or not in Python. Let us look into each of these approaches in detail with examples.

In this approach, we will check if the list is empty in Python using its boolean value. It is also called as **Truth Value Testing**.

According to Python Official docs, the following built-in objects are considered false:

- constants defined to be false:

and**None**

.**False** - zero of any numeric type:
,`0`

,`0.0`

,`0j`

,`Decimal(0)`

`Fraction(0, 1)`

- empty sequences and collections:
,`''`

,`()`

,`[]`

,`{}`

,`set()`

`range(0)`

Since an empty list is just an empty collection, it will be converted to a boolean value of

.**False**

There are two ways we can check this. Let us take an example to demonstrate both methods.

In the first approach if the list contains the value then the ** if **condition evaluates to

**if**

gets executed otherwise, the condition evaluates to **False**

and goes to the `else`

```
my_list = []
if my_list:
print("List is not Empty")
else:
print("List is Empty")
```

Output

`List is Empty`

The second approach is similar but we just do an inversion by using an `not`

in the

condition. In this case, if the list is empty the condition evaluates to **if**

. This is a better way to write code and also increases the readability of the code.**True**

```
my_list = []
if not my_list:
print("List is Empty")
else:
print("List is not Empty")
```

Output

`List is Empty`

The other approach is to check if the list is empty or not by using the

method. The **bool()**`bool()`

function returns the boolean value of an object, i.e., either `True`

or `False`

.

The approach is less common as we can achieve the desired results without using the `bool()`

method, as shown in the PEP-8 recommended style.

```
my_list = []
if bool(my_list):
print("List is not Empty")
else:
print("List is Empty")
```

Output

`List is Empty`

The `len()`

method is another popular way to check if the list is empty in Python. The `len()`

method returns the length of an argument passed to it. If the length is 0, it means the list is empty.

There are two techniques that can be used here.

The first technique is by using Truth Value Testing. If the list is empty, then the

method returns **len()**** 0**, which internally gets cast to the boolean value

`False`

.```
my_list = []
if len(my_list):
print("List is not Empty")
else:
print("List is Empty")
```

Output

`List is Empty`

The second technique is pretty simple. We will use the comparison operator to check if the length of the list is equal to 0. The main benefit of this technique is the code is more readable and easily understandable for Python beginners.

If the length of the list is equal to 0, then the condition satisfies, and we can conclude that it’s an empty list.

```
my_list = []
if len(my_list) == 0:
print("List is Empty")
else:
print("List is not Empty")
```

Output

`List is Empty`

This approach is fairly simple for beginners. Here we are comparing an existing list with a new empty list `[]`

inside an if condition. If the condition satisfies it means the list is empty and the if block gets executed otherwise it will execute the else block.

```
my_list = []
if my_list == []:
print("List is Empty")
else:
print("List is not Empty")
```

Output

`List is Empty`

There are several ways in Python to check if the list is empty, the most Pythonic way is to use the PEP-8 Style approach called **Truth Value Testing**. The other alternate approach is to use `len()`

method with the comparison operator or `bool()`

method.